首页 > 其他 > 详细

LeetCode-101 Symmetric Tree

时间:2015-03-29 00:29:08      阅读:253      评论:0      收藏:0      [点我收藏+]

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

题意:判断一颗树是否是镜像对称的。

解法1:使用DFS

public boolean isSymmetric(TreeNode root) {
       if(root == null)
            return true;
        return isSymmetric(root.left, root.right);
    }    

    public boolean isSymmetric(TreeNode left, TreeNode right) {
        if(left == null && right == null)
            return true;
        else if(left == null || right == null || left.val != right.val)
            return false;
        else 
            return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }

 

解法2:使用BFS

public boolean isSymmetric(TreeNode root) {
        if(root == null)
            return true;
        List<TreeNode> list = new ArrayList<TreeNode>();
        list.add(root);
        
        while(!list.isEmpty()) {
            int r = list.size() - 1;
            for(int l=0; l<r;) {
                TreeNode left = list.get(l);
                TreeNode right = list.get(r);
                if(left == null && right == null) {
                    list.remove(r);
                    list.remove(l);
                    r = r-2;
                } else if(left == null || right == null || left.val != right.val) {
                    return false;            
                } else {
                    l++;
                    r--;
                }
            }
            r = list.size();
            for(int i=0; i<r; i++) {
                TreeNode t = list.remove(0);
                if(t != null) {
                    list.add(t.left);
                    list.add(t.right);
                } else {
                    list.add(null);
                    list.add(null);
                }
            }
        }
        return true;
    }            

 

LeetCode-101 Symmetric Tree

原文:http://www.cnblogs.com/linxiong/p/4374989.html

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