LeetCode——101. 对称二叉树(递归、迭代)

101. 对称二叉树

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/symmetric-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目

给定一个二叉树,检查它是否是镜像对称的。
在这里插入图片描述
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?

思路

1、递归法

如果树为空或仅有根结点,对称;
如果仅有一个子树,不对称;
如果左右孩子数值相等继续以同样的标准检查左右子树直至叶子结点,都满足才可返回true,否则返回false

2、队列迭代法

如果树为空或仅有根结点,对称;
如果仅有一个子树,不对称;
将左右孩子入队,然后遍历队列,如果左孩子结点或右孩子结点为空或左右孩子结点值不等,则返回flase;
将遍历过的结点的左右孩子加入队列;如果遇到叶子结点,继续遍历别的结点;重复上述判断,所有都满足之后才可以返回true

代码

1、递归法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//1、递归法
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        if((root.left == null) && (root.right == null) ){//判空== null,不是=null
            return true;
        }
        return checkLR(root, root);
    }
    public boolean checkLR(TreeNode l, TreeNode r) {
        if(l == null && r == null){
            return true;
        }
        else if(l == null || r == null){
            return false;
        }
        if(l.val == r.val && checkLR(l.left, r.right) && checkLR(l.right,r.left)){
            return true;
        }
        else{
            return false;
        }
    }
}


2、队列迭代法

2、队列迭代法
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        if((root.left == null) && (root.right == null) ){//判空== null,不是=null
            return true;
        }
        return checkLR(root, root);
    }
    public boolean checkLR(TreeNode l, TreeNode r) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(l);
        queue.offer(r);
        while(!queue.isEmpty()){//不用queue != null
            l = queue.poll();
            r = queue.poll();
            if(l == null && r == null){
                continue;//注意此处不是return true
            }
            else if( (l == null || r == null) || (l.val != r.val)){
                return false;
            }
            queue.offer(l.left);   queue.offer(r.right);

            queue.offer(l.right);   queue.offer(r.left);
        }
        return true;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李霁明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值