L101. 对称二叉树/镜像二叉树

  1. 对称二叉树
    给定一个二叉树,检查它是否是镜像对称的。

非递推方法

class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        q.add(root);//加两次,每次判断两个
        
        while(!q.isEmpty()){
            TreeNode now1 = q.poll();
            TreeNode now2 = q.poll();
            //if(now1 != now2) return false;
            //上面这句是正常思路,但是其实应当判断是否都为null,一旦分支不同,结果自然不同
            if(now1 == null && now2 == null) continue;//不能直接返回true
            if(now1 == null || now2 == null) return false;
            if(now1.val != now2.val ) return false;
            //if(now1 != now2) return false;//这样写就不对了,二者的地址是不一定相同的
            q.add(now1.left);
            q.add(now2.right);
            q.add(now1.right);
            q.add(now2.left);
        }
        return true;
    }
}

2.递推方法

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return judge(root, root);
    }
    boolean judge(TreeNode r1, TreeNode r2){
        if(r1 == null && r2 == null) return true;
        if(r1 == null || r2 == null) return false;
        
        return r1.val == r2.val &&
                judge(r1.left,r2.right) && judge(r1.right, r2.left);
    }
}

在这里插入图片描述
这个主要利用队列交换的方法

public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null) return;
        LinkedList<TreeNode> q = new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()){
            root = q.poll();
            TreeNode tmp = root.left;
            root.left = root.right;
            root.right = tmp;
            if(root.left != null) q.add(root.left);
            if(root.right != null) q.add(root.right);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值