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     }




  • 相关阅读:
    Ural 1099 Work Scheduling (一般图的最大匹配:带花树算法)
    HDU 4687 Boke and Tsukkomi (2013.8.20 多校9 1002)(暴力+带花树算法)
    2013 Multi-University Training Contest 9 小结(2013.8.20)
    TeX代码模板(持续更新中)
    POJ 3177 Redundant Paths
    POJ 1904 King's Quest
    hdu 4685 Prince and Princess (2013.8.15 多校8---1010)
    2-SAT模板(修改自LRJ的模板)
    HDU 3622 Bomb Game
    Ubuntu 压缩命令
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8486422.html
Copyright © 2011-2022 走看看