有一棵有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;
}
本文介绍了一种使用深度优先搜索(DFS)算法来解决寻找二叉树中距离根节点最远节点的问题。通过定义二叉树结构并遍历每个节点,计算从根节点到各节点的距离,最终找到具有最远距离的节点。
839

被折叠的 条评论
为什么被折叠?



