判断一棵树是不是平衡二叉树
一棵树是平衡二叉树,当且仅当它的左右子树皆是平衡二叉树并且左右子树高度差小于绝对值 1 。
判断的方式和判断满二叉树的方式很相似。
完整代码如下:
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct node{
char val;
struct node* left;
struct node* right;
}TreeNode,*Tree;
//递归
/*一棵树是平衡二叉树,当且仅当左右子树都是平衡二叉树,且高度差绝对值不超过1。*/
int Height(Tree& t){
if(t == NULL) return 0;
return Height(t->left) > Height(t->right) ? Height(t->left) + 1 : Height(t->left) + 1;
}
bool isBalanced(Tree& t) {
if(t == NULL) return 1;
return abs(Height(t->left) - Height(t->right)) <= 1 && isBalanced(t->left) && isBalanced(t->right);
}
void CreateTree(Tree& t){
char x;
cin>>x;
if(x == '#') t = NULL;
else{
t = new TreeNode;
t->val = x;
CreateTree(t->left);
CreateTree(t->right);
}
}
int main(){
Tree t;
CreateTree(t);
/*
a b d # # e # # c f # # #
*/
cout<<"isBalanced:"<<endl;
cout<<isBalanced(t);
}
运行结果: