NYOJ 221 Tree

 1 #include <iostream>
 2 #include<cstdio> 
 3 #include <string>
 4 using namespace std;
 5 struct Node{
 6     char data;
 7     Node* lchild;
 8     Node* rchild;
 9 };
10 Node* CreateTree(string pre,string in)
11 {
12     Node* root = NULL;
13     if(pre.length()>0)
14     {
15         root = new Node;
16         root->data = pre[0];
17         int index = in.find(root->data);
18         root->lchild = CreateTree(pre.substr(1,index),in.substr(0,index));
19         root->rchild = CreateTree(pre.substr(index+1),in.substr(index+1));
20     }
21     return root;
22 }
23 
24 void PostOrder(Node* root)
25 {
26     if(root!=NULL)
27     {
28         PostOrder(root->lchild);
29         PostOrder(root->rchild);
30         cout<<root->data;
31     }
32 }
33 
34 int main()
35 {
36     string pre_str,in_str;
37     while (cin>>pre_str>>in_str)
38     {
39         Node* rt = CreateTree(pre_str,in_str);
40         PostOrder(rt);
41         cout<<endl;
42     }
43 }

posted on 2012-08-03 11:03  mycapple  阅读(264)  评论(0编辑  收藏  举报

导航