Class Solution
-
- All Implemented Interfaces:
public final class Solution3585 - Find Weighted Median Node in Tree.
Hard
You are given an integer
nand an undirected, weighted tree rooted at node 0 withnnodes numbered from 0 ton - 1. This is represented by a 2D arrayedgesof lengthn - 1, where <code>edgesi = u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub></code> indicates an edge from node <code>u<sub>i</sub></code> to <code>v<sub>i</sub></code> with weight <code>w<sub>i</sub></code>.The weighted median node is defined as the first node
xon the path from <code>u<sub>i</sub></code> to <code>v<sub>i</sub></code> such that the sum of edge weights from <code>u<sub>i</sub></code> toxis greater than or equal to half of the total path weight.You are given a 2D integer array
queries. For each <code>queriesj = u<sub>j</sub>, v<sub>j</sub></code>, determine the weighted median node along the path from <code>u<sub>j</sub></code> to <code>v<sub>j</sub></code>.Return an array
ans, whereans[j]is the node index of the weighted median forqueries[j].Example 1:
Input: n = 2, edges = [0,1,7], queries = [1,0,0,1]
Output: 0,1
Explanation:
Example 2:
Input: n = 3, edges = [0,1,2,2,0,4], queries = [0,1,2,0,1,2]
Output: 1,0,2
E****xplanation:
Example 3:
Input: n = 5, edges = [0,1,2,0,2,5,1,3,1,2,4,3], queries = [3,4,1,2]
Output: 2,2
Explanation:
Constraints:
<code>2 <= n <= 10<sup>5</sup></code>
edges.length == n - 1<code>edgesi == u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub></code>
<code>0 <= u<sub>i</sub>, v<sub>i</sub>< n</code>
<code>1 <= w<sub>i</sub><= 10<sup>9</sup></code>
<code>1 <= queries.length <= 10<sup>5</sup></code>
<code>queriesj == u<sub>j</sub>, v<sub>j</sub></code>
<code>0 <= u<sub>j</sub>, v<sub>j</sub>< n</code>
The input is generated such that
edgesrepresents a valid tree.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-