1. 程式人生 > >sdut oj2804 求二叉樹的深度(根據中序以及後序遍歷求樹)

sdut oj2804 求二叉樹的深度(根據中序以及後序遍歷求樹)

求二叉樹的深度

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;
}