【leetcode-101】 对称二叉树

本文提供了一种检查二叉树是否为镜像对称的方法,通过层次遍历和递归两种方式实现。层次遍历中,使用队列保存节点,并以列表形式记录每一层的节点值;递归方法中,则通过比较对称位置的子树来判断。

101. 对称二叉树

(1过)

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

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

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:

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

我的层次遍历:

注意由于下列情况null-3-null-3的存在,和一般的树的层次不一样:

    1
   / \
  2   2
   \   \
   3    3

public class SymmetricTree {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        boolean res = true;
        while (queue.size() > 0) {
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i=0;i<size;i++) {
                TreeNode node = queue.poll();
                if (node != null) {
                    queue.add(node.left);
                    queue.add(node.right);
                    list.add(node.val);
                } else {
                    list.add(null);
                }

            }
            if (!isSymmetric(list)){
                res = false;
            }

        }
        return res;
    }
    public boolean isSymmetric(ArrayList<Integer> list) {
        boolean flag = true;
        for (int i=0;i<list.size()/2;i++) {
            if (list.get(i) == null) {
                if (list.get(list.size()-1-i) != null)
                flag = false;
            }
            else if (!list.get(i).equals(list.get(list.size()-1-i)))
                flag = false;
        }
        return flag;
    }
}

 

递归:

关键:check(x.left, y.right) && check(x.right, y.left) 左左与右右对称,左右与右左对称

链接:https://www.nowcoder.com/questionTerminal/1b0b7f371eae4204bc4a7570c84c2de1
来源:牛客网

public class Solution {
  public static boolean isSymmetric(TreeNode root) {
        return check(root, root);
    }
    public static boolean check(TreeNode x, TreeNode y) {
        if(x == null && y == null) return true;
        if((x == null && y != null) || (x != null && y == null)) return false;
        return x.val == y.val && check(x.left, y.right) && check(x.right, y.left);
    }
}

 

转载于:https://www.cnblogs.com/twoheads/p/10598903.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值