UVa699

这个建树的根选的很有意思,在中间作为树的根。所以二叉树建树的方法虽然一般是有两种数组的方法,一个是如果深度不太大的话,可以之间用2*k+1,2*k建树,如果很大的话,就挨着建树,弄一个结构体,有左右子。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <map>
 5 #include <set>
 6 #include <algorithm>
 7 #include <fstream>
 8 #include <cstdio>
 9 #include <cmath>
10 #include <stack>
11 #include <queue>
12 using namespace std;
13 const double Pi=3.14159265358979323846;
14 typedef long long ll;
15 const int MAXN=100000+5;
16 const int dx[5]={0,0,0,1,-1};
17 const int dy[5]={1,-1,0,0,0};
18 const int INF = 0x3f3f3f3f;
19 const int NINF = 0xc0c0c0c0;
20 const ll mod=1e9+7;
21 int tree[MAXN];
22 void build(int c)
23 {
24     int m;cin>>m;
25     if(m!=-1) tree[c]+=m;
26         else return;
27     build(c-1);
28     build(c+1);
29 }
30 int main()
31 {
32     int root;int cnt=1;
33     while(cin>>root&&root!=-1)
34     {
35         memset(tree,0,sizeof(tree));
36         int mid=MAXN/2;
37         tree[mid]=root;
38         build(mid-1);
39         build(mid+1);
40         int ans=0;
41         printf("Case %d:\n",cnt++);
42         while(tree[ans]==0) ans++;
43         cout <<tree[ans++];
44         while(tree[ans]!=0)
45         {
46             cout <<" "<<tree[ans++];
47         }
48         cout <<endl<<endl;
49     }
50     return 0;
51 }

 

posted @ 2019-04-07 23:12  Chuhanjing  阅读(81)  评论(0编辑  收藏  举报