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 ofevery 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) {}
* };
*/
class Solution {
//采用后续遍历
bool isBalancedInt(TreeNode *root, int &depth)
{
if (!root)
{
depth = 0;
return true;
}
int leftLen = 0;
int rightLen = 0;
if (isBalancedInt(root->left, leftLen) && isBalancedInt(root->right, rightLen))
{
if (abs(leftLen - rightLen) > 1)
return false;
}
else
{
return false;
}
depth = (leftLen >= rightLen)? leftLen+1:rightLen+1;
return true;
}
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root)
return true;
int depth;
return isBalancedInt(root, depth);
}
};