Rebuilding a binary tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.