方法一:递归
1 /**
2 * Definition for a binary tree node.
3 * function TreeNode(val) {
4 * this.val = val;
5 * this.left = this.right = null;
6 * }
7 */
8 /**
9 * @param {TreeNode} root
10 * @return {boolean}
11 */
12 var isSymmetric = function(root) {
13 return root == null ? true : recur(root.left, root.right);
14 };
15
16 const recur = (left, right) => {
17 if(left == null && right == null) {
18 return true;
19 }
20 if(left == null || right == null || left.val != right.val) {
21 return false;
22 }
23 return recur(left.left, right.right) && recur(left.right, right.left);
24 }
方法二:栈
1 /**
2 * Definition for a binary tree node.
3 * function TreeNode(val) {
4 * this.val = val;
5 * this.left = this.right = null;
6 * }
7 */
8 /**
9 * @param {TreeNode} root
10 * @return {boolean}
11 */
12 var isSymmetric = function(root) {
13 if(root == null) return true;
14 let stack1 = [], stack2 = [];
15 let left = root.left, right = root.right;
16 while(stack1.length != 0 || stack2.length != 0 || left || right) {
17 while(left && right) {
18 stack1.push(left);
19 stack2.push(right);
20 left = left.left;
21 right = right.right;
22 }
23 if(left || right) {
24 return false;
25 }
26 left = stack1.pop();
27 right = stack2.pop();
28 if(left.val != right.val) {
29 return false;
30 }
31 left = left.right;
32 right = right.left;
33 }
34 return true;
35 };