二叉树——已知二叉树先序,建树,并输出中序、后序,并求树叶数和深度
2014-08-22 12:55
225 查看
Description 已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input 输入一个长度小于50个字符的字符串。Output输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。Sample Input
Input 输入一个长度小于50个字符的字符串。Output输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。Sample Input
abc,,de,g,,f,,,Sample Output
cbegdfa
cgefdba
3
5
#include <iostream> #include"cstdio" #include"cstring" #include"cstdlib" using namespace std; struct tree//定义一个结构体来进行存放各结点的信息以及其左右孩子的位置——用链表进行存储 { tree*l; tree*r; char data; }; tree*TREE(tree*p)//输入进各结点并建树 { char q; scanf("%c",&q); if(q==',')//某条支路结束标志 p=NULL; else { p=(tree*)malloc(sizeof(tree)); p->data=q; p->l=TREE(p); p->r=TREE(p); } return p; } void zhong(tree*p)//用递归来进行寻找输出 { if(p!=NULL) { zhong(p->l); printf("%c",p->data);//左结点为NULL,输出此时的结点信息data zhong(p->r);//继续从右子树进行寻找 } } void hou(tree*p) { if(p!=NULL) { hou(p->l); hou(p->r); printf("%c",p->data);//只有当左右子树都为NULL时,输出此结点信息 } } int sum=0; int node(tree*p) { if(p!=NULL) { node(p->l); node(p->r); if((p->l==NULL)&&(p->r==NULL))//一直寻找到树叶时,计数加1 sum++; } return sum; } int deep(tree*p)//先从根结点往左右子树找,不断寻找到树叶,然后从树叶往回一层层加1,一直到根结点 { int dl,dr; if(p==NULL)return 0;//碰到NULL时返回 dl=deep(p->l);//计算左子树深度 dr=deep(p->r);//计算右子树深度 dl=dl>dr?dl+1:dr+1;//比较左右子树此时深度,取最大的加上此结点的深度,即加1 return dl; } int main() { tree *root; root=(tree*)malloc(sizeof(tree)); root=TREE(root); zhong(root); putchar('\n'); hou(root); putchar('\n'); printf("%d\n",node(root)); printf("%d\n",deep(root)); return 0; }
相关文章推荐
- 已知二叉树先序、中序(中序、后序)遍历序列,输出后序(先序)遍历序列
- 已知二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列
- 二叉树系列(建树,前序,中序,后序,中序非递归,深度,叶子数,节点数)
- 已知二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列
- 已知二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列
- PAT树_层序遍历叶节点、中序建树后序输出、AVL树的根、二叉树路径存在性判定、奇妙的完全二叉搜索树、最小堆路径、文件路由
- 已知二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列
- 已知二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 先序和中序重建二叉树 后序输出
- 二叉树的中序、先序、后序、层序遍历 & 二叉树的深度 & 节点查找
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- Java 初始化二叉树,先序,中序,后序遍历,深度
- SDUT 1489 已知中序后序二叉树的先序,深度
- 与二叉树有关的一些操作:先序,中序,后序,层次遍历,计算深度,叶结点数
- 数据结构——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 【数据结构作业四】以二叉链表作存储结构,建立一棵二叉树,并输出该二叉树的先序、中序、后序遍历序列、高度和其叶子结点数。
- C语言二叉树常见操作详解【前序,中序,后序,层次遍历及非递归查找,统计个数,比较,求深度】
- 剑指offer面试题:输入某二叉树的前序遍历和中序遍历,输出后序遍历
- 根据后序与中序遍历建树层序遍历输出