首页 > 其他 > 详细

Leetcode--101. Symmetric Tree(easy)

时间:2019-02-11 11:05:09      阅读:198      评论:0      收藏:0      [点我收藏+]

  

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   /   2   2
 / \ / 3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   /   2   2
   \      3    3

recursively
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return root==null||judge(root.left,root.right);
    }
    
    public boolean judge(TreeNode l,TreeNode r){
        if(l==null||r==null)
            return l==r;
        if(l.val!=r.val)
            return false;
        return judge(l.left,r.right)&&judge(l.right,r.left);
    }
}

 

iteratively

public boolean isSymmetric(TreeNode root) {
    if(root==null)  return true;
    
    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode left, right;
    if(root.left!=null){
        if(root.right==null) return false;
        stack.push(root.left);
        stack.push(root.right);
    }
    else if(root.right!=null){
        return false;
    }
        
    while(!stack.empty()){
        if(stack.size()%2!=0)   return false;
        right = stack.pop();
        left = stack.pop();
        if(right.val!=left.val) return false;
        
        if(left.left!=null){
            if(right.right==null)   return false;
            stack.push(left.left);
            stack.push(right.right);
        }
        else if(right.right!=null){
            return false;
        }
            
        if(left.right!=null){
            if(right.left==null)   return false;
            stack.push(left.right);
            stack.push(right.left);
        }
        else if(right.left!=null){
            return false;
        }
    }
    
    return true;
}

 

Leetcode--101. Symmetric Tree(easy)

原文:https://www.cnblogs.com/albert67/p/10361101.html

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