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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
bool isBalancedRecurse(TreeNode *root, int *height)
{
if(!root)
{
*height = 0;
return true;
}
if(!root->left && !root->right)
{
*height = 1;
return true;
}
int lh = 0, rh = 0;
bool x = isBalancedRecurse(root->left,&lh);
bool y = isBalancedRecurse(root->right,&rh);
*height = max(lh,rh)+1;
return (abs(lh-rh)<=1 && x && y);
}
bool isBalanced(TreeNode *root) {
int height = 0;
return isBalancedRecurse(root,&height);
}
No comments:
Post a Comment