Tree problem(Tree & Graph)
Tree problem
Given a tree ofn
nodes. Theith
node's father isfa[i-1]
and the value of theith
node isval[i-1]
. Especially,1
represents the root,2
represents the second node and so on. We gurantee that-1
is the father of root(the first node) which means thatfa[0] = -1
.
The average value of a subtree is the result of the sum of all nodes in the subtree divide by the number of nodes in it.
Find the maximum average value of the subtrees in the given tree, return the number which represents the root of the subtree.
Example
Givenfa=[-1,1,1,2,2,2,3,3]
, representing the father node of each point, andval=[100,120,80,40,50,60,50,70]
, representing the value of each node, return1
.
Notice
the number of nodes do not exceed 100000 If there are more than one subtree meeting the requirement, return the minimum number.
分析
建图,这里graph key:val = parent:list of children
dfs图,返回[cnt,sum] 然后不断更新global的 MaxAvg和max index
结果返回max index,注意这里单个节点也要考虑在内。
Last updated