zoukankan      html  css  js  c++  java
  • 【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);
        }
    }
  • 相关阅读:
    这样的专家门诊
    CPU 知识介绍
    软考结束了!
    ubuntu环境配置eclipse+opencv
    2016年3月份总结
    点聚合功能基于ARCGIS RUNTIME SDK FOR ANDROID
    如何用java语言获取某个网页的源代码
    点聚合功能改良版本
    ARCGIS切图:TPK文件的空间参考为地理坐标系
    Java中的数据类型
  • 原文地址:https://www.cnblogs.com/twoheads/p/10598903.html
Copyright © 2011-2022 走看看