數據結構實驗之求二叉樹後序遍歷和層次遍歷(根據前序中序還原二叉樹)

數據結構實驗之求二叉樹後序遍歷和層次遍歷

Time Limit: 1000MS Memory limit: 65536K

題目描述

 已知一棵二叉樹的前序遍歷和中序遍歷,求二叉樹的後序遍歷。

輸入

 輸入數據有多組,第一行是一個整數t (t<1000),代表有t組測試數據。每組包括兩個長度小於50 的字符串,第一個字符串表示二叉樹的先序遍歷序列,第二個字符串表示二叉樹的中序遍歷序列。

輸出

每組第一行輸出二叉樹的後序遍歷序列,第二行輸出二叉樹的層次遍歷序列

示例輸入

2
abdegcf
dbgeafc
xnliu
lnixu

示例輸出

dgebfca
abcdefg
linux
xnuli


前序遍歷也叫先序遍歷。前序遍歷有一個特點,第一個節點爲二叉樹的根節點,根據這個根節點可以在中序序列中找到根節點的左右子樹。
例如:一個二叉樹前序序列是:a b d e g c f,中序序列是:d b g e a f c,則根據前序序列第一個數據爲a,在中序序列中可以看出此二叉樹的
左子樹爲:d b g e ,右子樹爲:f c ,此時就可以用遞歸解決了,前序序列指針往後移動一個位置即爲左子樹的根節點,前序序列指針往後移動左子樹節點個數加一個位置即爲
右子樹的根節點的位置。下面爲具體的代碼實現:
#include <stdio.h>
#include <stdlib.h>

typedef struct node//此處不解釋
{
    char data;
    struct node *lchild,*rchild;
}node,*nodeptr;


char xian[55],zhong[55];//定義兩個全局數組
//xian[]爲前序序列,zhong[]爲中序序列

struct node *Creat(char *xian,char *zhong,int n)
{//根據前序遍歷和中序遍歷建立二叉樹,n爲二叉樹包含節點個數
    struct node *T;
    int k;
    char *p;
    if(n<=0)return NULL;//當其包含結點數爲0,返回
    T=(struct node *)malloc(sizeof(struct node));
    T->data=*xian;
    for(p=zhong;p<zhong+n;p++)
    {
        if(*xian==*p)
            break;
    }
    k=p-zhong;
    T->lchild=Creat(xian+1,zhong,k);
    T->rchild=Creat(xian+k+1,p+1,n-k-1);
    return T;
}


int treelevel(struct node *T,int level)
{//層次遍歷輸出函數
    if(!T||level<0)
        return 0;
    if(level==0)
    {
        printf("%c",T->data);
        return 1;
    }
    return treelevel(T->lchild,level-1)+treelevel(T->rchild,level-1);
}


void level1(struct node *T)
{//二叉樹層次控制函數
    int i=0;
    for(i=0;;i++)
    {
        if(!treelevel(T,i))
            break;
    }
}


void lrd(struct node *T)
{//後序遍歷輸出函數
    if(T)
    {
        lrd(T->lchild);
        lrd(T->rchild);
        printf("%c",T->data);
    }
}


int main()
{
    int n,i;
    struct node *T;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",xian);
        scanf("%s",zhong);
        i=strlen(zhong);
        T=Creat(xian,zhong,i);
        lrd(T);
        printf("\n");
        level1(T);
        printf("\n");
    }
    return 0;
}

下面爲本人畫出的前幾步的運行步驟:

水平有限,不喜勿噴,原創辛苦,轉載請註明出處*>_<*
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章