您的位置:首页 > 其它

LeetCode: Balanced Binary Tree 解题报告

2014-12-18 20:54 281 查看
[b]Balanced Binary Tree [/b]

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.

Show Tags

// Solution 2:
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}

boolean cut = false;
if (root.right == null || root.left == null) {
cut = true;
}

return isBalanced(root.left) && isBalanced(root.right)
&& Math.abs(getDepth(root.left, cut) - getDepth(root.right, cut)) <= 1;
}

public int getDepth(TreeNode root, boolean cut) {
if (root == null) {
return -1;
}

if (cut && (root.left != null || root.right != null)) {
// if another tree is not deep, just cut and return fast.
// Improve the performance.
return 2;
}

return 1 + Math.max(getDepth(root.left, false), getDepth(root.right, false));
}


View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/IsBalanced.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: