二叉树的基础应用(建树+叶子数+深度+遍历 )
2014-12-23 13:06
225 查看
#include <stdio.h> #include <string.h> #include <string> #include <iostream> #include <algorithm> using namespace std; typedef struct node { char ch; struct node *ll; struct node *rr; }Binode, *Bitree; struct node *Creat_Bitree(struct node *root, char *s1, char *s2, int n) { if(n<=0) return NULL; else { root=new Binode; root->ch=s1[0]; int p = strchr(s2, s1[0])- s2; //在s2中查找s1[0]元素 root->ll= Creat_Bitree(root->ll, s1+1, s2, p); root->rr= Creat_Bitree(root->rr, s1+1+p, s2+1+p, n-1-p ); } return root; } void Post_order(Bitree p)//后序遍历 { if(p) { Post_order(p->ll); Post_order(p->rr); printf("%c", p->ch); } } void In_order(Bitree p)//中序遍历 { if(p) { Post_order(p->ll); printf("%c", p->ch); Post_order(p->rr); } } void Pre_order(Bitree p)//先序遍历 { if(p) { printf("%c", p->ch); Post_order(p->ll); Post_order(p->rr); } } int Deep_Bitree(Bitree p)//求二叉树的深度 { int deep1, deep2; if(p==NULL) return 0; else { deep1=Deep_Bitree(p->ll); deep2=Deep_Bitree(p->rr); if(deep1 > deep2) return (deep1+1); else return (deep2+1); } } void Leaf_num(Bitree p, int *cnt) //计算叶子节点的个数 { if(p==NULL) return ; else { Leaf_num(p->ll, cnt ); if(p->ll==NULL && p->rr==NULL ) { (*cnt)++; } Leaf_num(p->rr, cnt ); } } int main() { char s1[200]; char s2[200]; scanf("%s", s1); scanf("%s", s2); int len =strlen(s1); Bitree root; Bitree p; root = Creat_Bitree(p, s1, s2, len );//root是已经建好二叉树的根节点 p=root; Post_order(p); //从根点开始进行后序遍历 printf("\n"); p=root; int deep=Deep_Bitree(p); printf("%d\n", deep ); int a=0; int *sum; sum=&a; p=root; Leaf_num(p, sum); printf("%d\n", *sum); return 0; }
相关文章推荐
- 二叉树的三种遍历的应用(表达式,求深度,叶子数,结点数,二叉树的建立,复制)
- 二叉树的三种遍历的应用(表达式,求深度,叶子数,结点数,二叉树的建立,复制)
- 二叉树的深度、叶子数以及先、中、后、层次遍历
- 二叉树创建以及遍历(j简单创建、遍历、叶子计数、深度计数、销毁)之1
- 转载 二叉树的创建、遍历、深度、叶子节点数
- 二叉树的建树,按层遍历,结点总数,页结点,深度以及三序非递归遍历二叉树,建立中序线索二叉树
- 暑假集训 8.9 求二叉树的深度sdut2804 已知前中后中的两个序列建树及应用.
- 中序遍历二叉树的非递归的两种实现、线序遍历统计二叉树的叶子数、二叉树的深度
- 由先序遍历序列和中序遍历序列恢复二叉树以及统计叶子节点个数和树的深度
- 二叉树的创建、遍历、深度、叶子节点数
- 数据结构五:二叉树的递归遍历,二叉树的叶子节点个数,二叉树的拷贝操作基础学习
- 二叉树的前、中、后序遍历(递归和非递归)、层序遍历、深度、叶子节点个数
- 二叉树 遍历|统计叶子节点|求深度|交换左右子树|查找是否存在某个特定叶子节点练习题
- 二叉树,递归、非递归遍历,求深度,输出叶子节点
- C++二叉树的构建及求深度,叶子数量,层次遍历
- 数据结构--二叉树--求树的深度的算法(树遍历算法的应用)
- 八.二叉树各种操作的C语言实现 深度遍历求深度,广度遍历求深度,交换左右子树,求叶子节点数
- 二叉树叶子节点遍历---递归与非递归方法求取树深度
- 基本数据结构——二叉树的建立,遍历,求叶子节点,深度计算
- 【数据结构】二叉树的实现(如:默认成员函数、(叶子)节点数、深度、四种遍历)