• 【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);
        }
    }
  • 相关阅读:
    python爬虫之requests库
    python爬虫之urllib库
    fiddler配置及使用教程
    react中受控组件相关的warning
    Sublime Text 自动生成文件头部注释(版权信息):FileHeader 插件的使用
    手动安装sublime插件babel-sublime
    自定义组件 点击空白处隐藏
    pagination分页(支持首页,末页,跳转)
    vue打包以后,除了首页意外,其余页面是空白
    pm2踩过的坑
  • 原文地址:https://www.cnblogs.com/twoheads/p/10598903.html
Copyright © 2020-2023  润新知