您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐