The Falling Leaves UVa 699

The Falling Leaves

Problem
Given a binary tree, each node has a horizontal position: the left child is one unit to its left, and the right child is one unit to its right. The sum of the weights of all nodes at each horizontal position is output from left to right. As shown in the figure, the weight sums of the three positions from left to right are 7, 11, and 3, respectively. Enter in a recursive (preorder) fashion, using -1 to represent an empty tree.
Sample Input
5 7 -1 6 -1 -1 3 -1 -1
8 2 9 -1 -1 6 5 -1 -1 12 -1 -1 3 7 -1 -1 -1
-1
Sample Output
Case 1 :
7 11 3
Case 2:
9 7 21 15
insert image description here
Questions
Let's find the sum of the weights of each horizontal position, you can use an array to store the sum of the weights of each column. The
code is as follows

#include <iostream>
#include <cstring>
using namespace std;
const int maxn=128;
int sum[maxn];

void build(int p){
    
      //p是该节点的水平位置
    int v;
    cin>>v;
    if(v==-1)
        return; //(判断子树是不是)空树
    sum[p]+=v; //一边读入一边统计根本用不着创建树
    build(p-1);
    build(p+1);

}

bool init(){
    
    
    int v;
    cin>>v;
    if(v==-1)
        return false;
    memset(sum,0,sizeof (sum));
    int pos=maxn/2;  //树根的水平位置
    sum[pos]=v;                  //为什么不直接用build(pos)而要把树根单独提出来呢?这样不是增加了代码量吗?
                                 //这样做是为了判断这是不是一棵完完整整的空树,这和11行的是不一样的
    build(pos-1);
    build(pos+1);
}

int main()
{
    
    
    int kase=0;
    while(init()){
    
    
        int p=0;
        while(sum[p]==0)
            p++;        //找最左边的叶子
        cout<<"Case "<<++kase<<":\n"<<sum[p++]; //避免行末出现多余的空格
        while(sum[p]!=0)
            cout<<" "<<sum[p++];
        cout<<endl<<endl;
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325346948&siteId=291194637