[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 }
 
posted @ 2018-07-08 16:51  Lin.B  阅读(126)  评论(0编辑  收藏  举报