The problem:
Given a binary tree, check whether it is a mirror of the itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2/\/3 4 4 3
But the following are not:
1 / 2 2 \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
My Analysis:
The problem is little tricky, but it provoides a very important skill in sovling symmetric problem.
Key:the binary tree is the most instance to explore Sysmmetric properity.
Let's think in the this.
The tree A has its mirror B. If A is a sysmmetric tree <==> A and B should be the same.
Apparently, any move on B (left search or right search), it's equal to the Oppsite move on A. (B is the mirror image).
Thus we could use a to emmulate any move on B (just opposite the move).
Return Helper (cur_root1.left, cur_root2.right) && Helper (cur_root1.right, cur_root2.left);
Then, we could use the classic method of testing if the trees is matching, to test on tree A and B (imitate on A).
Public classSolution { Public Booleanissymmetric (TreeNode root) {if(Root = =NULL) return true; returnHelper (root, root); } Private BooleanHelper (TreeNode cur_root1, TreeNode cur_root2) {if(Cur_root1 = =NULL&& Cur_root2 = =NULL) return true; if(Cur_root1 = =NULL|| Cur_root2 = =NULL) return false; if(Cur_root1.val! =cur_root2.val)return false; returnHelper (Cur_root1.left, cur_root2.right) &&Helper (cur_root1.right, cur_root2.left); }}
[Leetcode#101] Symmetric Tree