SDNU 1015.最远路径(dfs)

Description

有一棵有n个节点的二叉树,它的节点编号为1到n,根节点编号是1,它的每条边都有一个给定的长度。请你求出该二叉树中距离根节点最远的节点的距离。

Input

第1行:一个数字n(1 <= n <= 100),表示该二叉树节点的数量。
第2至第n+1行:每行有三个整数(不会超过int),第i 行中的三个整数分别表示编号为i-1的节点与其父节点之间边的长度、编号为i-1的节点左孩子的编号和编号为i-1的节点右孩子的编号。

Output

最远的距离。

Sample Input

7
0 2 3
1 4 5
3 6 7
4 0 0
6 0 0
3 0 0
2 0 0

Sample Output

7
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
using namespace std;

struct node
{
    int len, lson, rson;
}a[100+8];

int n, best = 0;

void dfs(int id, int l, int r, int sum)
{
    sum += a[id].len;
    if(best<sum)best = sum;
    if(l != 0) dfs(l, a[l].lson, a[l].rson, sum);
    if(r != 0) dfs(r, a[r].lson, a[r].rson, sum);
}

int main()
{
    scanf("%d", &n);
    a[0].len = a[0].lson = a[0].rson = 0;
    for(int i = 1; i <= n; i++)
        scanf("%d%d%d", &a[i].len, &a[i].lson, &a[i].rson);
    dfs(1, a[1].lson, a[1].rson, 0);
    printf("%d
", best);
    return 0;
}
原文地址:https://www.cnblogs.com/RootVount/p/10927637.html