#include <iostream>
using namespace std;
int count = 0;
class BinTree{
public:
BinTree(int v){
value = v;
left = NULL;
right = NULL;
}
int value;
BinTree* left;
BinTree* right;
};
int max(int a,int b) {
return a>b?a:b;
}
void createTree(BinTree* &tree,int depth,int cur) {
if(cur < depth) {
tree = new BinTree(count);
count++;
createTree(tree->left,depth,cur+1);
createTree(tree->right,depth,cur+1);
} else {
return;
}
}
bool isBalance(BinTree* tree,int &height){
if(!tree) {
height = 0;
return true;
}
int lh,rh;
if(!isBalance(tree->left,lh))
return false;
if(!isBalance(tree->right,rh))
return false;
height = max(lh,rh) + 1;
if(abs(lh-rh) > 1)
return false;
return true;
}
int main(){
BinTree* tree = new BinTree(0);
BinTree* leftTree;
BinTree* rightTree;
createTree(leftTree,11,0);
createTree(rightTree,10,0);
tree->left = leftTree;
tree->right = rightTree;
int height;
cout<<(isBalance(tree,height)?"true":"false")<<endl;
cout<<height<<endl;
return 0;
}
判断二叉树是否平衡,计算树的高度
最新推荐文章于 2023-02-07 20:48:49 发布