NYOJ 題目756 重建二叉樹

來源:互聯網
上載者:User
重建二叉樹 時間限制: 1000 ms  |  記憶體限制: 65535 KB 難度: 3 描述 題目很簡單,給你一棵二叉樹的後序和中序序列,求出它的前序序列(So easy!)。 輸入 輸入有多組資料(少於100組),以檔案結尾結束。
每組資料僅一行,包括兩個字串,中間用空格隔開,分別表示二叉樹的後序和中序序列(字串長度小於26,輸入資料保證合法)。 輸出 每組輸出資料單獨佔一行,輸出對應得先序序列。 範例輸入
ACBFGED ABCDEFGCDAB CBAD
範例輸出
DBACEGF

BCAD

由後序遍曆和中序遍曆來推匯出先序遍曆。在做這樣的題時,得勤用紙和筆,將各序列的縮圖畫出來,這樣就把思路開拓了。


先序遍曆:r L R

中序遍曆:L r R

後序遍曆:L R r

#include <iostream>#include <fstream>#include <string.h>#include <string>using namespace std;void build(int n,char* s1,char* s2,char* s){    if(n<=0) return ;    int p=strchr(s2,s1[n-1])-s2;    build(p,s1,s2,s+1);    build(n-p-1,s1+p,s2+p+1,s+p+1);    s[0]=s1[n-1];}int main(void){  //  fstream cin("題目765.txt");    int n;    char s1[50],s2[50],ans[50];    while(cin>>s1>>s2)    {        n=strlen(s1);        build(n,s1,s2,ans);        ans[n]='\0';        cout<<ans<<endl;    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.