SDNU__1015.最远路径


有一棵有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

dfs

根据输入定义好一个二叉树,然后用dfs搜索,存储最大值

#include<iostream>
#include<cstdio>
#include<cmath>
#include<memory.h>
using namespace std;
struct node{
	int sf;
	int lz;
	int rz;
}a[105];
int tree[105][2];
int gen;
int n;
int retmax = -99;
void dfs(int x,int mys)
{
	for(int j = 0;j < 2;j++)
	{
		if(tree[x][j] == 0)break; 
		dfs(tree[x][j],mys + a[tree[x][j]].sf);
	}
	if(mys > retmax)
	{
		retmax = mys;
	}
}
int main()
{
	
	cin>>n;
	memset(tree,0,sizeof(tree));
	for(int i = 1;i <= n;i++)
	{
		cin>>a[i].sf>>a[i].lz>>a[i].rz;
		tree[i][0] = a[i].lz;
		tree[i][1] = a[i].rz;
	}
	dfs(1,0);
	cout<<retmax<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值