重建二叉樹,二叉樹

來源:互聯網
上載者:User

重建二叉樹,二叉樹
重建二叉樹時間限制:1000 ms  |  記憶體限制:65535 KB難度:3

描述
題目很簡單,給你一棵二叉樹的後序和中序序列,求出它的前序序列(So easy!)。
輸入
輸入有多組資料(少於100組),以檔案結尾結束。
每組資料僅一行,包括兩個字串,中間用空格隔開,分別表示二叉樹的後序和中序序列(字串長度小於26,輸入資料保證合法)。
輸出
每組輸出資料單獨佔一行,輸出對應得先序序列。
範例輸入
ACBFGED ABCDEFGCDAB CBAD
範例輸出
DBACEGFBCAD
來源
原創
上傳者

TC_黃平

資料結構會遍曆,會還原。。只是代碼實現太弱。。

參考代碼來源:http://blog.csdn.net/whjkm/article/details/39341331#comments

#include<cstdio>#include<cstdlib>#include<cstring>struct node{char value;node *lchild,*rchild;};node * newnode(char c){node *p=(node *)malloc(sizeof(node));    p->value=c;p->lchild=p->rchild=NULL;return p;}node *rebuild(char *post,char *in,int n){if(n==0) return NULL;char ch=post[n-1];node *p;p=newnode(ch);int i;for(i=0;i<n && in[i]!=ch;i++);int l_len=i;int r_len=n-i-1;if(l_len>0) p->lchild=rebuild(post,in,l_len);if(r_len>0) p->rchild=rebuild(post+l_len,in+l_len+1,r_len);return p;}void preorder(node *p){if(p==NULL) return ;     printf("%c",p->value); preorder(p->lchild); preorder(p->rchild);}int main(){char postorder[100],inorder[100];while(scanf("%s%s",&postorder,&inorder)!=EOF){node *tr=rebuild(postorder,inorder,strlen(postorder));        preorder(tr);printf("\n");}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.