首页 > 其他 > 详细

[LeetCode#101]Symmetric Tree

时间:2015-01-11 06:07:49      阅读:307      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/airwindow/p/4216056.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!