如何求二叉树的高度(递归实现)
来源:互联网 发布:淘宝客返利是什么意思 编辑:程序博客网 时间:2024/05/01 10:16
核心代码
比较左右子树的高度,把高的那个子树+1返回,就是整棵树的高度
int Height(BiTreeNode *head){if(head==NULL) return 0;else{int m=Height(head->LeftChild);int n=Height(head->RightChild);return (m>n)? (m+1):(n+1);}}
完整代码:
#include<iostream>#include<assert.h>using namespace std; typedef struct Lnode{char data;struct Lnode *LeftChild;struct Lnode *RightChild;}BiTreeNode;void Initiate(BiTreeNode **head){(*head)=(BiTreeNode *)malloc(sizeof(BiTreeNode));assert((*head)!=NULL); //if the judging conditio is true,this statement is not executed(*head)->LeftChild=NULL;(*head)->RightChild=NULL;}BiTreeNode * InsertLeftChild(BiTreeNode *head,char a ){if(head==NULL) return NULL;BiTreeNode * p,*t;t=head->LeftChild;p=(BiTreeNode *)malloc(sizeof(BiTreeNode));assert(p!=NULL);p->data=a;p->RightChild=NULL;p->LeftChild=t;head->LeftChild=p;return head->LeftChild;}BiTreeNode *InsertRightChild(BiTreeNode *head,char a){if(head==NULL) return NULL;BiTreeNode *p,*t;t=head->RightChild;p=(BiTreeNode *)malloc(sizeof(BiTreeNode));assert(p!=NULL);p->data=a;p->LeftChild=NULL;p->RightChild=t;head->RightChild=p;return head->RightChild;}void Destroy(BiTreeNode *head){if(head!=NULL && head->LeftChild!=NULL)Destroy(head->LeftChild);if(head!=NULL && head->RightChild!=NULL)Destroy(head->RightChild);free(head);}void LDR(BiTreeNode *head){if(head!=NULL){LDR(head->LeftChild);cout<<head->data<<" ";LDR(head->RightChild);}}int Height(BiTreeNode *head){if(head==NULL) return 0;else{int m=Height(head->LeftChild);int n=Height(head->RightChild);return (m>n)? (m+1):(n+1);}}void main(){BiTreeNode *head,*p,*q;Initiate(&head);head->data='g';p=InsertLeftChild(head,'a');p=InsertLeftChild(p,'b');p=InsertRightChild(head,'c');LDR(head);cout<<endl;cout<<"the height:"<<Height(head)<<endl;Destroy(head);system("pause");}
0 0
- 如何求二叉树的高度(递归实现)
- 求二叉树的高度(非递归)
- 递归求二叉树的高度
- 递归求二叉树的高度
- 层次遍历求二叉树的高度(非递归)
- 4-8 求二叉树高度 *(递归)
- java语言实现的二叉树的各种操作(包括递归与非递归遍历二叉树,求二叉树的高度,节点总数,叶子节点等)
- 求二叉树的深度(或高度)的非递归算法
- 二叉树各种遍历的实现(递归、非递归、层次、高度和节点数目)
- 二叉树如何实现双亲结点及求树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- 求二叉树的高度
- NSHTTPURLResponse中获取Status Code和Error Code 和 Header内容
- HDU1255 覆盖的面积 【扫描线】
- _snprintf 使用的一点错误记录
- 数据结构java版二 自定义结构
- Linux:安装双系统(Win7+Ubuntu)后,Ubuntu正常,Win7无法启动
- 如何求二叉树的高度(递归实现)
- PHP中利用jQuery操作json格式数据,实现$_POST的数据传输和接收
- JAVA基础知识
- 开机自启动
- JAVA面试题
- s3c2440裸机开发环境的搭建
- SQL 之Group by with Rollup 的效果
- android应用添加桌面快捷方式
- Quicksort