- 第一种方法:采用自底向上的递归方法
int height( TreeNode* root){
if(root == NULL){
return 0;
}else{
int leftheight = height(root->left);
int rightheight = height(root->right);
if(leftheight == -1 || rightheight == -1 || abs(leftheight-rightheight)>1){
return -1;
}else{
return max(rightheight,leftheight)+1;
}
}
}
bool isBalanced(TreeNode* root) {
return height(root) >= 0;
}
- 第二种方法:
int height(TreeNode* root){
if(root == NULL){
return 0;
}else{
int left = height(root->left);
int right = height(root->right);
return max(left,right) + 1;
}
}
bool isBalanced(TreeNode* root) {
if(root == NULL){
return true;
}else{
if(abs(height(root->left)-height(root->right))<=1 && isBalanced(root->left)
&& isBalanced(root->right)){
return true;
}else{
return false;
}
}
}
- 求树高:
int height(TreeNode *T){
if(T == NULL){
return 0;
}else{
int leftheight = height(T->left);
int rightheight = height(T->right);
return max(leftheight,rightheight)+1;
}
}