Skip to content

Commit ef23e2b

Browse files
Symmetric Tree
1 parent 9690690 commit ef23e2b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

EASY/src/easy/SymmetricTree.java

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package easy;
2+
3+
import classes.TreeNode;
4+
5+
/**101. Symmetric Tree
6+
7+
Total Accepted: 121737
8+
Total Submissions: 346738
9+
Difficulty: Easy
10+
11+
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
12+
13+
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
14+
15+
1
16+
/ \
17+
2 2
18+
/ \ / \
19+
3 4 4 3
20+
21+
But the following [1,2,2,null,3,null,3] is not:
22+
23+
1
24+
/ \
25+
2 2
26+
\ \
27+
3 3
28+
29+
Note:
30+
Bonus points if you could solve it both recursively and iteratively. */
31+
public class SymmetricTree {
32+
//a very natural idea flows out using recursion. Cheers.
33+
public boolean isSymmetric(TreeNode root) {
34+
if(root == null) return true;
35+
return isSymmetric(root.left, root.right);
36+
}
37+
38+
private boolean isSymmetric(TreeNode left, TreeNode right) {
39+
if(left == null || right == null) return left == right;
40+
if(left.val != right.val) return false;
41+
return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
42+
}
43+
44+
public static void main(String... strings) {
45+
SymmetricTree test = new SymmetricTree();
46+
TreeNode root = new TreeNode(1);
47+
System.out.println(test.isSymmetric(root));
48+
}
49+
}

0 commit comments

Comments
 (0)