zoukankan      html  css  js  c++  java
  • LC.101.Symmetric Tree

    https://leetcode.com/problems/symmetric-tree/description/
    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
    /
    2:n1 2:n2
    / /
    3 4 4 3
    But the following [1,2,2,null,3,null,3] is not:
    1
    /
    2:n1 2:n2

    3 3

    判断二叉树是否是平衡树,比如有两个节点n1, n2,我们需要
    1: 先比较 n1的值 和 n2 的值是否相等
    2: n1的左子节点的值和n2的右子节点的值是否相等,
    3: 同时还要比较n1的右子节点的值和n2的左子结点的值是否相等,以此类推比较完所有的左右两个节点
    比较典型的PRE-ORDER 和 第 100题:Same Tree 综合来看
    time: o(n)
    space: o(n)
     1 public boolean isSymmetric(TreeNode root) {
     2         //corner case
     3         if (root == null) return true ;
     4         return helper(root.left, root.right) ;
     5     }
     6 
     7     private boolean helper(TreeNode n1, TreeNode n2){
     8         if (n1 == null && n2 == null) return true ;
     9         else if(n1 == null&& n2!=null ) return false;
    10         else if (n1 != null && n2 == null) return false ;
    11         //pre-order compare n1.left with n2.right && n1.right with n2.left
    12         //开始比较,如果不满足条件,就没有必要往下走了
    13         14             if (n1.val != n2.val){
    15                 return false ;
    16             }
    17             //n1.left n1.right n2.left n2.right 判断的情况不需要考虑,因为已经在开头做了判断
    18 19         //往下走 给出左右
    20         boolean leftCheck = helper(n1.left, n2.right) ;
    21         boolean rightCheck = helper(n1.right, n2.left) ;
    22         //返回来,综合左右 往上面返回值: 其实 n1.val == n2.val 前面已经进行判断了,但是我这里还是写上,好理解。
    23         return leftCheck && rightCheck && n1.val == n2.val ;
    24     }




  • 相关阅读:
    linux shell script
    API Gateway : Kong
    rabbitmq management advance lesson
    Python Base HTTP Server
    linux 笔试题
    dll return a string
    friend class
    GCC 编译使用动态链接库 LD
    设计模式学习(四)——单例模式
    简单聊聊TestNG中的并发
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8486422.html
Copyright © 2011-2022 走看看