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 binary tree
* 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;
bool res=(abs(treeheight(root->left)-treeheight(root->right))<=1)&&(isBalanced(root->left))&&(isBalanced(root->right));
return res;
}
int treeheight(TreeNode *node){
if(!node) return 0;
return 1+max(treeheight(node->left),treeheight(node->right));
}
};