數據結構基礎 復原二叉樹

原題

復原二叉樹

Time Limit: 1 Sec Memory Limit: 32 MB


Description

小明在做數據結構的作業,其中一題是給你一棵二叉樹的前序遍歷和中序遍歷結果,要求你寫出這棵二叉樹的後序遍歷結果。

Input

輸入包含多組測試數據。每組輸入包含兩個字符串,分別表示二叉樹的前序遍歷和中序遍歷結果。每個字符串由不重複的大寫字母組成。

Output

對於每組輸入,輸出對應的二叉樹的後續遍歷結果。

Sample Input


DBACEGF ABCDEFG
BCAD CBAD

Sample Output


ACBFGED
CDAB

代碼

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
using namespace std;
string A,B;
int n;
struct node
{
    char val;
    node *ch[2];
};

//在B中尋找非葉子結點位置
int Search(char x,string b,int n)
{
    for(int i=0;i<n;i++)
    {
        if(x==b[i])
        {
            return i;
        }
    }
    return 0;
}
//復原二叉樹
node *Restore(string A,string B,int n)
{
    if(n<=0)
    {
        return NULL;
    }
    node *p=new node();
    p->val=A[0];
    p->ch[0]=p->ch[1]=NULL;
    int i=Search(A[0],B,n);
    //左子樹遞歸,右子樹遞歸
    p->ch[0]=Restore(A.substr(1),B,i);
    p->ch[1]=Restore(A.substr(1+i),B.substr(i+1),n-1-i);
    return p;
}
//後序遍歷
void Postorder(node *t)
{
    if(t==NULL)
    {
        return;
    }
    Postorder(t->ch[0]);
    Postorder(t->ch[1]);
    printf("%c",t->val);
}

int main()
{
    //freopen("in.txt","r",stdin);
    while(cin>>A>>B)
    {
        n=A.size();
        node *root=Restore(A,B,n);
        Postorder(root);
        cout<<endl;
    }
    return 0;
}


發佈了25 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章