5.已知平衡二叉樹(shù)節(jié)點(diǎn)的定義為
Struct Node{double value_; Node* lc_; Node* rc_;int bf_;}
其中bf_為節(jié)點(diǎn)的平衡因子(左子高減去右子高)。完成下面算法,它求平衡二叉樹(shù)的高度。
int height(Node* root);
要求其復(fù)雜度為O(㏒n),其中n為二叉樹(shù)節(jié)點(diǎn)的個(gè)數(shù)。
/*****************************************************************************/
/*===================================================================*/
/*****************************************************************************/
#include<iostream>
using namespace std;
#define SIZE 6
struct Node{
double value_;
Node* lc_;
Node* rc_;
int bf_;
};
int height(Node* root) //題目中要求設(shè)計(jì)的函數(shù);
{
int floor=0;
while(root->lc_!=NULL||root->rc_!=NULL){
floor++;
if(root->bf_>=0){
root=root->lc_;
}
else{
root=root->rc_;
}
}
return floor+1;
}
int main()
{
int hight=0;
Node tree[SIZE];
for(int i=0;i<SIZE;i++){ //構(gòu)造二叉樹(shù);
tree[SIZE].value_=i;
}
tree[0].bf_=1; tree[1].bf_=0;
tree[2].bf_=1; tree[3].bf_=0;
tree[4].bf_=0; tree[5].bf_=0;
tree[0].lc_=&(tree[1]);
tree[0].rc_=&(tree[2]);
tree[1].lc_=&(tree[3]);
tree[1].rc_=&(tree[4]);
tree[2].lc_=&(tree[5]);
tree[2].rc_=NULL;
tree[3].lc_=NULL;
tree[3].rc_=NULL;
tree[4].lc_=NULL;
tree[4].rc_=NULL;
tree[5].lc_=NULL;
tree[5].rc_=NULL;
hight=height(tree); //題中函數(shù)的運(yùn)用;
cout<<"默認(rèn)二叉樹(shù)的高度為:"<<hight<<endl<<endl;
system("pause");
return 0;
}
/*****************************************************************************/
/*===================================================================*/
/*****************************************************************************/
聯(lián)系客服