求二叉树的深度
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2 dbgeafc dgebfca lnixu linux
示例输出
4 3
提示
对于一课二叉树,如果他的左子树和右子树都为空,那么此时只有一个结点,根据二叉树的深度定义,此时二叉树的深度为1;若二叉树为空,约定二叉树的深度为0;对于其他情况,先求出其左右子树的深度depthL和depthR,那么整棵二叉树的深度为1+max(depthL+depthR).其左右子树的深度计算和上述过程相似,根据这种思想,可以得到球二叉树深度的递归算法。
坐标定位:
<span style="font-size:14px;">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElemType;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
char a[100];
BiTree InPostOrder(char inord[],char postord[],int i,int j,int k,int h)
//中序序列为从i到j,先序序列为从k到h;
{
BiTree T;
int m;
if (j<0||h<0)
T = NULL;
else
{
T = (BiTree)malloc(sizeof (BiTNode));
if (!T)
return 0;
T->data = postord[h];
m = i;
while (inord[m]!=postord[h])
m++;
if (m==i)
T->lchild = NULL;
else T->lchild = InPostOrder(inord,postord,i,m-1,k,m-i+k-1);
if (m==j)
T->rchild = NULL;
else T->rchild = InPostOrder(inord,postord,m+1,h,m,h-1);
}
return T;
}
int Depth(BiTree T)
{
int depthval;
if (!T)
depthval = 0;
else
{
int depthLeft = Depth(T->lchild);
int depthRight = Depth(T->rchild);
depthval = 1 + (depthLeft > depthRight ? depthLeft : depthRight);
}
return depthval;
}
int main()
{
int t,n;
BiTree T;
char postord[100],inord[100];
scanf ("%d",&t);
while (t--)
{
scanf ("%s",inord);
scanf ("%s",postord);
n = strlen(inord);
T = InPostOrder(inord,postord,0,n-1,0,n-1);
int k = Depth(T);
printf ("%d\n",k);
}
return 0;
}
</span>
长度定位:
<pre name="code" class="cpp">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ElemType char
typedef struct BiTreeNode
{
ElemType data;
struct BiTreeNode *lchild,*rchild;
}BiTreeNode,*BiTree;
BiTree build(BiTree p,char *post,char *ino,int n)
{
if (n<=0)
return NULL;
else
{
p = (BiTree) malloc (sizeof (struct BiTreeNode));
p->data = post[n-1];
int k = strchr (ino,post[n-1])- ino;
p -> lchild = build(p->lchild,post,ino,k);
p -> rchild = build (p->rchild,post+k,ino+k+1,n-k-1);
}
return p;
}
int BiTreeDepth(BiTree root)
{
int d=0,depthl,depthr;
if (root == NULL)
return 0;
if (root -> lchild == NULL && root -> rchild == NULL)
return 1;
depthl = BiTreeDepth(root -> lchild);
depthr = BiTreeDepth(root -> rchild);
if (depthl > depthr)
d = depthl;
else d = depthr;
return d+1;
}
int main ()
{
int t;
char post[100],ino[100];
BiTree root;
scanf ("%d",&t);
while (t--)
{
scanf ("%s",ino);
scanf ("%s",post);
root = build (root,post,ino,strlen(post));
printf ("%d\n",BiTreeDepth(root));
}
return 0;
}
本文介绍了一种根据二叉树的中序遍历和后序遍历序列来计算二叉树深度的方法,并提供了完整的C语言实现代码。通过递归算法,文章详细解释了如何构建二叉树并计算其深度。
5177

被折叠的 条评论
为什么被折叠?



