题目描述:
题目思路:
1.依旧二叉树的DFS
2.建树过程中开个数组统计
//紫书源代码WA
AC代码:
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 5 const int maxn = 100 ; 6 int sum[maxn] ; 7 8 void buildtree(int val,int p) //建树,p为树根的水平位置 9 { 10 int vl,vr; 11 if(val == -1) return ; 12 sum[p] += val ; 13 cin >> vl ; 14 buildtree(vl,p - 1); 15 cin >> vr ; 16 buildtree(vr,p + 1); 17 } 18 19 int main(int argc, char *argv[]) 20 { 21 int k=0,v; 22 while(cin >> v && v != -1){ 23 memset(sum,0,sizeof(sum)) ; 24 int pos = maxn/2 ; 25 buildtree(v,pos) ; 26 int p = 0; 27 while(sum[p] == 0) p++ ; //最左边的子叶 28 cout << "Case " << ++k << ":\n" << sum[p++]; 29 while(sum[p] != 0) { 30 cout << " " << sum[p]; 31 p++; 32 } 33 cout << "\n\n"; 34 } 35 return 0; 36 }