数据结构实验之二叉树八:(中序后序)求二叉树的深度

来源:互联网 发布:linux crontab 日志 编辑:程序博客网 时间:2024/06/10 03:29

Problem Description

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

输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
Output

输出二叉树的深度。
Example Input

2
dbgeafc
dgebfca
lnixu
linux
Example Output

4
3

#include <iostream>using namespace std;#include <stdio.h>#include <stdlib.h>#include <string.h>#include <cstring>typedef char telemtype;typedef struct Binode{    telemtype data;    struct Binode *lchild,*rchild;} Binode,*Bitree;void creat(Bitree &T,telemtype a[],telemtype b[],int n){    int i;    if(n==0)        T=NULL;    else    {        for(i=0; i<n; i++)        {            if(a[i]==b[n-1])                break;        }        T=new Binode;        T->data=b[n-1];//n是从1开始的        creat(T->lchild,a,b,i);//a,b都是从左开始。有长度就行        creat(T->rchild,a+i+1,b+i,n-i-1);//n为总个数,i为左子树个数,1为根个数    }}int depth(Bitree T){    int m,n,d;    if(!T)        d=0;    else if(!T->lchild&&!T->rchild)        d=1;    else    {        m=depth(T->lchild);        n=depth(T->rchild);        d=1+(m>n ? m:n);//加上根    }    return d;}int main(){    int t;    int n;    telemtype a[55],b[55];    cin>>t;    while(t--)    {        Bitree T;        scanf("%s",a);        scanf("%s",b);        n=strlen(a);//计算字符串的长度是从1开始的,但是数组是从0开始存的        creat(T,a,b,n);        n=depth(T);        cout<<n<<endl;    }    return 0;}
#include <stdio.h>#include <stdlib.h>#include <iostream>#include <string.h>using namespace std;typedef char telemtype;typedef struct Binode{    telemtype data;    struct Binode *lchild,*rchild;}Binode,*Bitree;Bitree creat(Bitree &T,telemtype a[],telemtype b[], int n){    int i;    if(n==0)        T=NULL;    else    {        T=new Binode;        T->data=b[n-1];        for(i=0;i<n;i++)        {            if(a[i]==b[n-1])                break;        }        T->lchild=creat(T->lchild,a,b,i);        T->rchild=creat(T->rchild,a+i+1,b+i,n-i-1);    }    return T;}int depth(Bitree T){    int d;    int m,n;    if(!T)        d=0;    else if(!T->lchild&&!T->rchild)        d=1;    else    {        m=depth(T->lchild);        n=depth(T->rchild);        d=1+(m>n?m:n);    }    return d;}int main(){    int t;    telemtype a[60],b[60];    cin>>t;    while(t--)    {        cin>>a>>b;        Bitree T;        int n;        n=strlen(a);        T=creat(T,a,b,n);        n=depth(T);        cout<<n<<endl;    }}
阅读全文
2 0
原创粉丝点击