求二叉树的深度

来源:互联网 发布:淘宝账号是什么 从哪看 编辑:程序博客网 时间:2024/05/29 04:05

题目描述

已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。

输入

输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。

输出

输出二叉树的深度。

示例输入

2dbgeafcdgebfcalnixulinux

示例输出

43
#include <stdio.h>#include <stdlib.h>#include <string.h>struct node{   char data;   struct node*l,*r;};struct node*creat(char *a,char *b,int m){    struct node*t;    char *p;    if(m==0)        return NULL;    t=(struct node*)malloc(sizeof(struct node));    t->data=*b;    for(p=a;p;p++)    {       if(*p==*b)        break;    }    int k=p-a;    t->r=creat(p+1,b-1,m-1-k);    t->l=creat(a,b-m+k,k);     return t;}int depth(struct node*t){   int del,der;   if(!t)return 0;   if(t)   {       del=depth(t->l);       der=depth(t->r);       if(del>der)        return del+1;       else return der+1;   }}int main(){    struct node*t;    int n,m;    char a[60],b[60];    scanf("%d",&n);    while(n--)    {      scanf("%s",a);      scanf("%s",b);      m=strlen(a);      t=creat(a,&b[m-1],m);      int x=depth(t);      printf("%d\n",x);    }    return 0;}

0 0
原创粉丝点击