sdut oj2804 求二叉树的深度(根据中序以及后序遍历求树)
2016-08-09 15:29
309 查看
题目链接:点击打开链接
求二叉树的深度
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。输入
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。输出
输出二叉树的深度。示例输入
2 dbgeafc dgebfca lnixu linux
示例输出
4 3
提示
代码实现:#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; struct Tree { char data; Tree *lchild,*rchild; }; char a[110],b[110]; ///根据中序遍历与后序遍历求出二叉树 Tree *Creat(int n,char a[],char b[]) { if(n == 0) return NULL; char *p; Tree *T; T = new Tree; T->data = b[n - 1];///树根是当前树中所有元素在后序遍历中最后出现的元素 for(p = a; *p != '\0'; p++)///找出根节点在中序遍历中的位置 { if(*p == b[n - 1]) break; } int t = p - a; T->lchild = Creat(t,a,b);///根左边的元素就是左子树的全部元素,递归 T->rchild = Creat(n - t - 1,p + 1,b + t);///根右边的就是右子树的全部元素,递归求解 return T; } int Depth(Tree *T) { int ldepth,rdepth; if(!T) return 0; else { ldepth = Depth(T->lchild); rdepth = Depth(T->rchild); return ldepth > rdepth ? ldepth+1 : rdepth+1; } } int main() { int n; while(~scanf("%d",&n)) { while(n--) { memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); Tree *T; scanf("%s%s",a,b); int len = strlen(a); T = Creat(len,a,b); printf("%d\n",Depth(T)); } } return 0; }
相关文章推荐
- 根据前序遍历和中序遍历构建二叉树以及根据中序遍历后序遍历构建二叉树
- poj2255 根据二叉树的前序和中序遍历 求出树的后序遍历
- 用非递归实现二叉树的前序、中序、后序、层次遍历,用递归实现查找、统计个数、比较、求深度
- poj2255 根据任意二叉树的先序遍历和中序遍历求解后序遍历
- 由先序遍历序列和中序遍历序列恢复二叉树以及统计叶子节点个数和树的深度
- 二叉树的创建以及利用迭代实现中序、先序、后序遍历、清空
- 二叉树的创建、先序、中序以及后序遍历
- LeetCode: 106_Construct Binary Tree from Inorder and Postorder Traversal | 根据中序和后序遍历构建二叉树 | Medium
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- Python练手之根据前序和中序&根据中序和后序重建二叉树,输出前序、中序和后序遍历结果
- 二叉树的创建以及利用迭代实现中序、先序、后序遍历、清空
- 二叉树的创建,先序、中序、后序遍历的递归实现以及层序遍历
- 二叉树建立以及先序、中序、后序、层次遍历(JAVA 实现)
- 二叉树的创建 前序 中序 后序遍历以及最大值与最小值的差
- 与二叉树有关的一些操作:先序,中序,后序,层次遍历,计算深度,叶结点数
- 根据后序和中序遍历重建二叉树
- 根据后序和中序遍历重建二叉树
- 二叉树的非递归前序、中序以及后序遍历C++模版类实现
- 二叉树基本操作的递归实现(二叉树建立,先序,中序,后序,深度的递归遍历。广度优先,高度优先的非递归遍历)
- [C/C++] 先序建立二叉树| 先序、中序、后序遍历二叉树| 求二叉树深度、节点数、叶节点数 算法实现