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.
解题思路:先写一个统计深度的函数。然后计算根节点的左右子树的深度,并做差,判断是否大于1.然后递归的思想,再分别以左右子树为根节点进行递归判断。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
int l=countDepth(root->left);
int r=countDepth(root->right);
if(l-r>1||r-l>1) return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
int countDepth(TreeNode* root){
if(!root) return 0;
return max(countDepth(root->left),countDepth(root->right))+1;
}
};