File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 3+ Date: Dec 25, 2014
4+ Problem: Symmetric Tree
5+ Difficulty: Easy
6+ Source: https://oj.leetcode.com/problems/symmetric-tree/
7+ Notes:
8+ Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
9+ For example, this binary tree is symmetric:
10+ 1
11+ / \
12+ 2 2
13+ / \ / \
14+ 3 4 4 3
15+ But the following 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+ Solution: 1. Recursive solution
25+ */
26+
27+ /**
28+ * Definition for binary tree
29+ * public class TreeNode {
30+ * int val;
31+ * TreeNode left;
32+ * TreeNode right;
33+ * TreeNode(int x) { val = x; }
34+ * }
35+ */
36+ public class Solution {
37+ public boolean isSymmetric (TreeNode root ) {
38+ if (root == null ) return true ;
39+ return solve (root .left , root .right );
40+ }
41+ public boolean solve (TreeNode t1 , TreeNode t2 ) {
42+ if (t1 == null && t2 == null ) return true ;
43+ if (t1 == null && t2 != null || t1 != null && t2 == null || t1 .val != t2 .val ) return false ;
44+ return solve (t1 .left , t2 .right ) && solve (t1 .right , t2 .left );
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments