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 }
     
  • 相关阅读:
    python-ConfigParser模块【读写配置文件】
    MinGW安装和使用
    mybatis批量操作
    SSM框架的简单搭建
    idea录制宏
    数据导出,导入
    JS中调用android和ios系统手机打开相机并可选择相册功能
    get请求中url传参中文乱码问题
    hibernate criteria中Restrictions的用法
    hibernate报错
  • 原文地址:https://www.cnblogs.com/boris1221/p/9280518.html
Copyright © 2011-2022 走看看