Rebuilding a binary tree
Rebuilding binary tree time limit: 1000 MS | memory limit: 65535 KB difficulty: 3
-
Description
-
The question is very simple. I will give you a post-order and mid-order sequence of a binary tree and find its pre-order sequence (So easy !).
-
Input
-
The input contains multiple groups of data (less than 100 groups), ending with a file.
Each group contains only one row of data, including two strings separated by spaces, indicating the post-order and Middle-order sequences of Binary Trees (the string length is less than 26, and the input data is valid ).
-
Output
-
Each group of output data occupies a single row. The output data must be sorted first.
-
Sample Input
-
ACBFGED ABCDEFGCDAB CBAD
-
Sample output
-
DBACEGFBCAD
-
Source
-
Original
-
Uploaded
TC _ Huang Ping
The data structure will be traversed and restored .. But the code implementation is too weak ..
Reference code source: 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;}