问题:
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.
分析:又见Binary tree,又是递归。
代码:
class Solution {
public:
int isBalancedHelper(TreeNode *root) {
if (!root) return 0;
int left = isBalancedHelper(root->left);
int right = isBalancedHelper(root->right);
if (left == -1 || right == -1) return -1;
if (left - right <= 1 && right - left <= 1)
return max(left, right) + 1;
else
return -1;
}
bool isBalanced(TreeNode *root) {
return isBalancedHelper(root) != -1;
}
};