【题目描述】
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==NULL) return true;
int leftheight=treeheight(root->left);
int rightheight=treeheight(root->right);
if(isBalanced(root->left)&&isBalanced(root->right)){
if(abs(leftheight-rightheight)<=1) return true;
else return false;
}
return false;
}
int treeheight(TreeNode* root){
if(root==NULL) return 0;
return max(treeheight(root->left),treeheight(root->right))+1;
}
};