zoukankan      html  css  js  c++  java
  • [leetcode] Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced.

    For this problem, a height-balanced binary tree is defined as:

    a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    Example 1:

    Given the following tree [3,9,20,null,null,15,7]:

        3
       / 
      9  20
        /  
       15   7

    Return true.

    Example 2:

    Given the following tree [1,2,2,3,3,null,null,4,4]:

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    Return false.


     分析:题目关键在于平衡树的定义:每个节点的左右子树高度都不超过1。注意每个节点,再联想到求树的高度方法,很容易想到这个题目用DFS做。下面就是找到DFS的递归结束和返回。
        不难想到递归结束的条件是root==null,这个时候返回0。
        关于递归的返回,在这里卡了一下,因为不太熟练DFS,后来参考了一下discuss才想明白。
        下面先贴上正常求二叉树高度的代码:
    1     private int maxDepth(TreeNode root){
    2         if ( root == null ) return 0;
    3         else return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
    4     }

        根据上面代码的思路和上面的分析,本题的代码如下:

     1 class Solution {
     2     boolean isbalanced = true;
     3     public boolean isBalanced(TreeNode root) {
     4         helper(root);
     5         return isbalanced;
     6     }
     7     private int helper(TreeNode root) {
     8         if ( root == null ) return 0;
     9         int left = helper(root.left);
    10         int right = helper(root.right);
    11         if ( Math.abs(left-right) > 1 ) isbalanced=false;
    12         return Math.max(left,right)+1;
    13     }
    14 }
     
  • 相关阅读:
    (转)干货|一次完整的性能测试,测试人员需要做什么?
    (转)JMeter性能测试-服务器资源监控插件详解
    【Android Apk重新签名报错re-sign.jar之解决方法】
    CrackMe_001
    判断二叉树是否是镜像对称
    顺时针打印矩阵
    利用前序遍历和中序遍历构造二叉树
    二叉树的四种遍历方式
    最长回文子串
    同步/异步/阻塞/非阻塞
  • 原文地址:https://www.cnblogs.com/boris1221/p/9280518.html
Copyright © 2011-2022 走看看