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 everynode never differ by more than 1.
Recursive:
bool balance(TreeNode* root, int &depth)
{
if(root == NULL)
{
depth = 0;
return true;
}
int leftdepth = 0;
bool left = balance(root->left, leftdepth);
int rightdepth = 0;
bool right = balance(root->right, rightdepth);
depth = leftdepth > rightdepth ? leftdepth+1 : rightdepth+1;
int gap = leftdepth - rightdepth;
return left && right && (-1 <= gap && gap <= 1);
}
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int depth = 0;
return balance(root, depth);
}