The Falling Leaves 简单的遍历+建树

本文介绍了一种在树形结构中计算相同竖直位置节点值之和的方法。通过定义节点位置并在遍历时累加同一位置的节点值实现。文章提供了完整的C++代码实现,包括树的构建与遍历。

大意:给你一棵树,让你求竖直位置相同的节点的和

和一般的建树 + 遍历没什么不同的,不过需要在树的结构体里面加一个 pos 记录节点位置,再用一个数字储存节点的和

#include<cstdio>
#include<cstring>
#include<iostream>
#include<malloc.h>
using namespace std;
#define MAX_SIZE 100000
#define Base 10000
int counts[MAX_SIZE];
int visa  [MAX_SIZE];
struct Tree
{
    int value;
    int pos;
    Tree *Left;
    Tree *Right;
};
Tree *BuildTree(int pos){ /*构建一棵树*/
    int valued;
    Tree *node = (Tree*)malloc(sizeof(Tree));
    scanf("%d",&valued);
    if(valued == -1){
        node = NULL;
        return node;
    }
    else {
        node -> value = valued;
        node -> pos = pos;
        node -> Left =  BuildTree(pos - 1);
        node -> Right = BuildTree(pos + 1);
        return node;
    }
}
void dfs(Tree *node){
    if(node == NULL)
        return ;
    else {
        int p = node -> pos;
        counts[Base + p] += node -> value;
        visa[Base + p] = 1; /*记录是否被访问过*/
        dfs(node -> Left);
        dfs(node -> Right);
        return ;
    }
}
int main()
{
    int Case = 1;
    while(true){
        Tree *root;
        memset ( counts, 0 , sizeof(counts) );
        memset ( visa, 0 , sizeof(visa) );
        root = BuildTree(0);
        if(root == NULL)  break;
        dfs(root);
        printf("Case %d:\n",Case);
        for(int i = 0,k = 0 ;i < MAX_SIZE; i++ )
            if(visa[i]&&k == 0){
            k = 1;
            printf("%d",counts[i]);
            }
            else if(visa[i]){
                printf(" %d",counts[i]);
            }
        printf("\n\n");
        Case++;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值