首页 > 代码库 > [LeetCode#101]Symmetric Tree

[LeetCode#101]Symmetric Tree

The problem:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1   /   2   2 / \ / 3  4 4  3

 

But the following is 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 an very important skill in sovling symmetric problem.
Key: the binary tree is the best instance to explore sysmmetric properity.
Let‘s think in this way.
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 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 two trees are matching, to test on tree A and B(imitate on A).

public class Solution {    public boolean isSymmetric(TreeNode root) {        if (root == null)            return true;            return helper(root, root);    }        private boolean helper(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;                return helper(cur_root1.left, cur_root2.right) && helper(cur_root1.right, cur_root2.left);    }}

 

[LeetCode#101]Symmetric Tree