您的位置:首页 > 其它

LeetCode 110 Balanced Binary Tree

2016-04-06 23:45 357 查看
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 boolean isBalanced(TreeNode root) {
return depth(root) >= 0;
}

public int depth(TreeNode root) {
if (root == null) return 0;
int highL = depth(root.left);
int highR = depth(root.right);
if (Math.abs(highL - highR) > 1 || highL < 0 || highR < 0) return -1;
return Math.max(highL, highR) + 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: