码迷,mamicode.com
首页 > 其他好文 > 详细

Balanced Binary Tree

时间:2015-05-05 18:52:21      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/balanced-binary-tree/

https://leetcode.com/discuss/28162/java-o-n-solution-based-on-maximum-depth-of-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.

public class Solution {
private boolean result = true;

public boolean isBalanced(TreeNode root) {
    maxDepth(root);
    return result;
}

public int maxDepth(TreeNode root) {
    if (root == null)
        return 0;
    int l = maxDepth(root.left);
    int r = maxDepth(root.right);
    if (Math.abs(l - r) > 1)
        result = false;
    return 1 + Math.max(l, r);
}
}

 

 1 public class Solution {
 2     public boolean isBalanced(TreeNode root) {
 3         if (root == null)
 4             return true;
 5         if (Math.abs(height(root.left)-height(root.right)) <= 1)
 6             return (isBalanced(root.left) && isBalanced(root.right));
 7         return false;
 8     }
 9     public int height(TreeNode root) {
10         if (root == null)
11             return 0;
12         int left = height(root.left);
13         int right= height(root.right);
14         return (Math.max(left,right)+1);
15 
16     }
17 }

 

Balanced Binary Tree

标签:

原文地址:http://www.cnblogs.com/qq1029579233/p/4479671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!