Rebuilding the binary tree time limit: +Ms | Memory Limit:65535KB Difficulty:3
-
-
Describe
-
The topic is very simple, give you a binary tree after the order and the sequence, to find its pre-order sequence (so easy!).
-
-
Input
-
-
input has multiple sets of data (less than 100 groups), ending with the end of the file.
Each group of data is only one row, including two strings, separated by a space, respectively, the order and sequence of the binary tree (string length is less than 26, input data to ensure legal).
-
-
Output
-
-
each set of output data takes a single row, and the output corresponds to a sequence of first order.
-
-
Sample input
-
-
Acbfged Abcdefgcdab Cbad
-
-
Sample output
-
-
Dbacegfbcad
-
-
Source
-
-
Original
-
Uploaded by
Tc_ Huang Ping
The data structure is traversed and will be restored. Just 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);p rintf ("\ n");} return 0;}
Rebuilding a binary tree