-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path101. Symmetric Tree.js
More file actions
35 lines (31 loc) · 846 Bytes
/
101. Symmetric Tree.js
File metadata and controls
35 lines (31 loc) · 846 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
if (root === null) return true;
invertTree(root.right);
return isSameTree(root.left, root.right);
};
function invertTree(root) {
if (root === null) return;
var tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
invertTree(root.right);
return;
}
function isSameTree(left, right) {
if (left && right === null) return false;
if (left === null && right) return false;
if (left === null && right === null) return true;
return (left.val === right.val) && isSameTree(left.left, right.left) && isSameTree(left.right, right.right);
}