LeetCode刷题笔录Symmetric Tree

50 篇文章 0 订阅
30 篇文章 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.

先搞recursive的吧,感觉简单一点。

给定两个节点,判断是否对称的条件是:

两个节点值相等;

left的left child等于right的right child;

left的right child等于right的left child.

然后递归判断(left.left, right.right)和(left.right, right.left)

public class Solution {
    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;
        if((left == null && right != null) || (left != null && right == null))
            return false;
        if(left.val != right.val)
            return false;
        return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }
}

Now comes the non-recursive version. The basic idea is to perform an altered version of level-order traversal. Each time we retrieve two elements from the queue and perform a similar judgement of the recursive one. 

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null)
            return true;
        if(root.left == null && root.right == null)
            return true;
        if(root.left == null && root.right != null)
            return false;;
        if(root.left != null && root.right == null)
            return false;
        //make a queue to perform an altered version of level-order traversal
        LinkedList<TreeNode> q = new LinkedList<TreeNode>();
        q.addLast(root.left);
        q.addLast(root.right);
        
        while(q.size() >= 2){
            TreeNode left = q.pollFirst();
            TreeNode right = q.pollFirst();
            if(left.val != right.val)
                return false;
            if((left.left == null && right.right != null) || (left.left != null && right.right == null))
                return false;
            if((left.right == null && right.left != null) || (left.right != null && right.left == null))
                return false;
            
            if(left.left != null && right.right != null){
                q.addLast(left.left);
                q.addLast(right.right);
            }
            if(left.right != null && right.left != null){
                q.addLast(left.right);
                q.addLast(right.left);
            }
        }
        
        return true;
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值