二叉树建立和遍历
来源:互联网 发布:荣誉勋章2010优化 编辑:程序博客网 时间:2024/06/05 02:35
#include "stdio.h"#include "string.h"#include "malloc.h"#define NULL 0typedef struct BiTNode{ //定义数据结构char data;struct BiTNode *lchild,*rchild;}BiTNode,*BiTree;BiTree Create(BiTree T) //建立二叉树{ char ch; ch=getchar(); if(ch=='#') T=NULL; else { if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) printf("Error!"); T->data=ch; T->lchild=Create(T->lchild); T->rchild=Create(T->rchild); } return T;}void Preorder(BiTree T){ //先序遍历二叉树 if(T) { printf("%c",T->data); Preorder(T->lchild); Preorder(T->rchild); }}int Sumleaf(BiTree T){ //求叶子节点的个数 int sum=0,m,n; if(T) { if((!T->lchild)&&(!T->rchild)) sum++; m=Sumleaf(T->lchild); sum+=m; n=Sumleaf(T->rchild); sum+=n; }return sum;} void zhongxu(BiTree T){ if(T) { zhongxu(T->lchild); printf("%c",T->data); zhongxu(T->rchild); }}void houxu(BiTree T){ //后续遍历 if(T) { houxu(T->lchild); houxu(T->rchild); printf("%c",T->data); }}int Depth(BiTree T) //求二叉树的深度{int dep=0,depl,depr;if(!T) dep=0; else { depl=Depth(T->lchild); depr=Depth(T->rchild); dep=1+(depl>depr?depl:depr); }return dep;}void main(){BiTree T;int sum,dep;T=Create(T);Preorder(T);printf("\n");zhongxu(T);printf("\n");houxu(T);printf("\n");sum=Sumleaf(T);printf("%d",sum);dep=Depth(T);printf("\n%d",dep);}
例如输入序列ABC##DE#G##F###(其中的“#”表示空,并且输入过程中不要加回车,因为回车也有对应的ASCII码,是要算字符的,但是输入 完之后可以按回车退出),这时候就能够看到结果了。
另外你必须会手动建立一棵二叉树,保证你输入的序列能构成一棵二叉树,否则你怎么输入,按最后按多少回车程序也不会结束!
原文请戳此处
0 0
- 二叉树建立和遍历
- 二叉树建立和遍历
- 二叉树建立和遍历
- 二叉树建立和遍历
- 二叉树建立和遍历
- 二叉树建立和遍历
- 二叉树的建立和遍历
- 二叉树 普通的 建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- Tree 二叉树的建立 和遍历
- 二叉树的建立和遍历
- [转]二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 递归建立和遍历二叉树等
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- Could not reliably determine the server's fully qualified domain name, using LAMP1.1 for ServerName
- 链接过程分析(四)---ELF文件之可执行文件分析(max)
- Fatal error: Call to a member function generateDesignExceptionSub() on a non-object
- [快速配置]Sersync
- 虚拟机Windows不能识别USB设备
- 二叉树建立和遍历
- iOS:图片的旋转方向问题
- 数据库学习笔记1
- 小团队的技术管理
- 欢迎使用CSDN-markdown编辑器
- 基于XMPP的IOS聊天客户端程序(XMPP服务器架构)
- 基于XMPP的IOS聊天客户端程序(IOS端一)
- eclipse导入Android Launcher3运行
- Phoenix 4.3.0 与 Hbase0.98.10-hadoop2的整合