Tree diameter 树的直径II

这道题相对于binary tree diameter I + maximum path sum binary tree II +图的DFS

牛客: https://www.nowcoder.com/practice/a77b4f3d84bf4a7891519ffee9376df3?tpId=196&tqId=37158&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-total%2Fquestion-ranking&tab=answerKey

题目描述

给定一棵树,求出这棵树的直径,即树上最远两点的距离。包含n个结点,n-1条边的连通图称为树。 示例1的树如下图所示。其中4到5之间的路径最长,是树的直径,距离为5+2+4=11 示例1

输入

复制

6,[[0,1],[1,5],[1,2],[2,3],[2,4]],[3,4,2,1,5]

返回值

复制

11

2.思路

maximum path sum binary tree II的思路 + dfs的多个branch的tree的思路

1通过dictionary建树,key为parent,value= list of (child node, edge weight) pair

2.遍历tree的每一个node,找到每个branch的从上往下加起来的max path sum,找到max path sum最大的两个branch,并把两个branch的max path sum相加得到跨越两个branch的path的pathsum, 然后和global max path sum对比更新

3返回找到的最大的从上往下的max path sum + current node的值得到目前最大的path sum

Last updated

Was this helpful?