[Problem]
[Solution]
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.
[Solution]
/**说明:版权所有,转载请注明出处。 Coder007的博客
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// isBalanced
bool isBalanced(TreeNode *root, int &height){
// null node
if(root == NULL){
height = 0;
return true;
}
// height of the left brunch and right brunch
int leftH = 0, rightH = 0;
bool left = isBalanced(root->left, leftH);
bool right = isBalanced(root->right, rightH);
// update height
height = max(leftH, rightH) + 1;
// balanced
if(left && right && abs(leftH - rightH) <= 1){
return true;
}
else{
return false;
}
}
// isBalanced
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int height = 0;
return isBalanced(root, height);
}
};