Leetcode 101. 对称二叉树

题目

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

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

在这里插入图片描述
说明:

  • 如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

解答

解法一:递归

本题是 Leetcode 100. 相同的树 的变种题。

Leetcode 100. 相同的树 可看我上篇博客:上篇博客。

本题递归思路:

  1. 如果当前值不相等,结束。
  2. 否则因为为镜像树,所以需要递归 (n1.left, n2.right) 以及 (n1.right, n2.left)。
代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return isSymmetric(root.left, root.right);
    }
    
    private boolean isSymmetric(TreeNode n1, TreeNode n2) { 
        if(n1 == null) return n2 == null;
        if(n2 == null) return n1 == null;
        return n1.val == n2.val && isSymmetric(n1.left, n2.right) && isSymmetric(n1.right, n2.left);
    }
}
结果

在这里插入图片描述

解法二:队列 + 迭代

这道题和 Leetcode 100. 相同的树 没有太大区别,只是稍微变化了一点。

同样的方法可以解决本题。

详情见:上篇博客。

代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    class Couple {
        TreeNode n1;
        TreeNode n2;
        
        Couple(TreeNode n1, TreeNode n2) {
            this.n1 = n1;
            this.n2 = n2;
        }
    }
    
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        
        LinkedList<Couple> queue = new LinkedList<>();
        queue.offer(new Couple(root.left, root.right));
        while(!queue.isEmpty()) {
            Couple top = queue.poll();
            TreeNode n1 = top.n1;
            TreeNode n2 = top.n2;
            if(!equals(n1, n2)) return false;
            
            if(n1 != null && n2 != null) {
                queue.offer(new Couple(n1.left, n2.right));
                queue.offer(new Couple(n1.right, n2.left));
            }
        }
        
        return true;
    
    }
    
    private boolean equals(TreeNode p, TreeNode q) {
        if(p == null) return q == null;
        if(q == null) return p == null;
        return p.val == q.val;
    }
}
结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值