打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
球平衡二叉树高函数int height(Node* root);

5.已知平衡二叉树节点的定义为

Struct Node{double value_; Node* lc_; Node* rc_;int bf_;}

其中bf_为节点的平衡因子(左子高减去右子高)。完成下面算法,它求平衡二叉树的高度。

int height(Node* root);

要求其复杂度为O(㏒n),其中n为二叉树节点的个数。

/*****************************************************************************/

/*===================================================================*/

/*****************************************************************************/

#include<iostream>

using namespace std;

 

#define SIZE 6

struct Node{

       double value_;

       Node* lc_;

       Node* rc_;

       int bf_;

};

 

int height(Node* root)                        //题目中要求设计的函数;

{

       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++){                   //构造二叉树;

              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);                         //题中函数的运用; 

       cout<<"默认二叉树的高度为:"<<hight<<endl<<endl;

    system("pause");

       return 0;

}

 

 程序中构造的二叉树如下:

/*****************************************************************************/

/*===================================================================*/

/*****************************************************************************/

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
AVL树及其实现
【查找结构3】平衡二叉查找树 [AVL]
《算法导论》读书笔记之第10章 基本数据结构之二叉树
LeetCode实战:二叉树的最大深度
二叉树的几种存储方式(一个数组,指针形式,两个数组)
动画:二叉树有几种存储方式?(上)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服