Uva--548 (二叉树,遍历,重建)

2014-06-19 00:27:02

题意&思路:给出一棵二叉树的中序遍历和后序遍历,让你求出从根节点到任意叶节点路径上节点值总合的最小值。思路就是根据两个遍历建树,DFS搜索之。

非常感谢http://blog.csdn.net/acvcla/article/details/27554837?reload的精简代码,借鉴了!

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 const int maxn = 100000005;
 6 
 7 int in[10005],post[10005],tmin,tag;
 8 struct node{
 9     int val;
10     node *left,*right;
11     node(){
12         val = 0;
13         left = right = NULL;
14     }
15 };
16 node * Build_tree(int *in,int *post,int cnt){
17     if(cnt <= 0)
18         return NULL;
19     node *next = new node;
20     int pos;
21     for(pos = 0; pos < cnt ; ++pos)
22         if(in[pos] == post[0])
23             break;
24     if(pos > 0)
25         next->left = Build_tree(in,post + cnt - pos,pos);
26     if(pos < cnt - 1)
27         next->right = Build_tree(in + pos + 1,post + 1,cnt - pos - 1);
28     next->val = post[0];
29 
30     return next;
31 }
32 void Dfs(node *tem,int sum){
33     if(tem == NULL)
34         return;
35     if(tem->left == NULL && tem->right == NULL){
36         if(sum + tem->val < tmin){
37             tmin = sum + tem->val;
38             tag = tem->val;
39         }
40     }
41     Dfs(tem->left,sum + tem->val);
42     Dfs(tem->right,sum + tem->val);
43 }
44 void Delete(node *tem){
45     if(!tem)
46         return;
47     if(tem->left != NULL)
48         Delete(tem->left);
49     if(tem->right != NULL)
50         Delete(tem->right);
51     delete tem;
52     tem = NULL; //Important
53 }
54 int main(){
55     char t;
56     node *root;
57     while(scanf("%d",&in[0]) == 1){
58         root = NULL;
59         int cnt = 1;
60         while((t = getchar()) != '\n'){
61             scanf("%d",in + cnt);
62             ++cnt;
63         }
64         for(int i = cnt - 1; i >= 0; --i){
65             scanf("%d",post + i);
66         }
67         tmin = tag = maxn;
68         tag = 0;
69         root = Build_tree(in,post,cnt);
70         Dfs(root,0);
71         printf("%d\n",tag);
72 
73         Delete(root);
74     }
75     return 0;
76 }

 

posted @ 2014-06-19 00:30  Naturain  阅读(122)  评论(0编辑  收藏  举报