UVa 699 The Falling Leaves
题意:给出按先序输入的一颗二叉树,分别求出从左到右的相同横坐标上的节点的权值之和
递归建树,然后用sum数组分别统计每一个横坐标上的权值之和
感觉建树都在递归递归递归= =慢慢理解吧
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include <cmath> 5 #include<algorithm> 6 using namespace std; 7 8 typedef long long LL; 9 const int maxn=2000; 10 int sum[maxn]; 11 12 void build(int p){ 13 int v; 14 cin>>v; 15 if(v==-1) return; 16 sum[p]+=v; 17 build(p-1);//建左子树 18 build(p+1);//建右子树 19 } 20 21 bool init(){ 22 int v; 23 cin>>v; 24 if(v==-1) return false; 25 memset(sum,0,sizeof(sum)); 26 int pos=maxn/2; 27 sum[pos]=v; 28 // printf("init被调用\n"); 29 build(pos-1);build(pos+1); 30 } 31 32 int main() 33 { 34 int kase=0; 35 while(init()){ 36 int p=0; 37 while(sum[p]==0) p++; 38 cout<<"Case "<<++kase<<":\n"<<sum[p++]; 39 while(sum[p]!=0) cout<<" "<<sum[p++]; 40 cout<<"\n\n"; 41 } 42 return 0; 43 }
go---go--go