Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ed111d6

Browse files
Symmetric Tree
1 parent acb19b6 commit ed111d6

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

LeetcodeProblems/Symmetric_Tree.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Symmetric Tree
3+
4+
https://leetcode.com/problems/symmetric-tree/description/
5+
6+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
7+
8+
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
9+
10+
1
11+
/ \
12+
2 2
13+
/ \ / \
14+
3 4 4 3
15+
But the following [1,2,2,null,3,null,3] is not:
16+
1
17+
/ \
18+
2 2
19+
\ \
20+
3 3
21+
Note:
22+
Bonus points if you could solve it both recursively and iteratively.
23+
*/
24+
25+
/**
26+
* Definition for a binary tree node.
27+
* function TreeNode(val) {
28+
* this.val = val;
29+
* this.left = this.right = null;
30+
* }
31+
*/
32+
/**
33+
* @param {TreeNode} root
34+
* @return {boolean}
35+
*/
36+
var isSymmetric = function(root) {
37+
if(root === null)
38+
return true;
39+
return isSymetricAux(root.left, root.right);
40+
};
41+
42+
var isSymetricAux = function(root1, root2) {
43+
if(root1 === null)
44+
return root2 === null;
45+
46+
if(root2 === null || root1.val !== root2.val) {
47+
return false;
48+
}
49+
50+
return isSymetricAux(root1.left, root2.right) && isSymetricAux(root1.right, root2.left);
51+
}

0 commit comments

Comments
 (0)