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.
class Solution {
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root){
if((height(root->left)-height(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right))
return true;
return false;
}
return true;
}
int height(TreeNode *root){
if(root==NULL)return 0;
return (height(root->left)>height(root->right)?height(root->left):height(root->right))+1;
}
};
class Solution {
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int depth=0;
return is_Balance_tree(root,depth);
}
bool is_Balance_tree(TreeNode *root , int &height)
{
int left,right;
if(!root){
height=0;
return true;
}
if(is_Balance_tree(root->left,left) && is_Balance_tree(root->right,right)){
if(abs(left-right)<=1){
height=1+((left>right)?left:right);
return true;
}
}
return false;
}
};
上面第一个算法是普通的递归的方法,里面包含了很多重复计算树的高度的过程,其实我们仔细想一下,在计算的时候可以采用后序遍历的方式,这样就可以自底向上不停的记录树的高度,实现一次遍历就可以得到这棵树是否为平衡二叉树