Rebuilding a binary tree

Source: Internet
Author: User

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;}

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.