Find Weighted Median Node in Tree Problem
Description
LeetCode Problem 3585.
You are given an integer n and an undirected, weighted tree rooted at node 0 with n nodes numbered from 0 to n - 1. This is represented by a 2D array edges of length n - 1, where edges[i] = [u_i, v_i, w_i] indicates an edge from node u_i to v_i with weight w_i.
The weighted median node is defined as the first node x on the path from u_i to v_i such that the sum of edge weights from u_i to x is greater than or equal to half of the total path weight.
You are given a 2D integer array queries. For each queries[j] = [u_j, v_j], determine the weighted median node along the path from u_j to v_j.
Return an array ans, where ans[j] is the node index of the weighted median for queries[j].
Example 1:
Input: n = 2, edges = [[0,1,7]], queries = [[1,0],[0,1]]
Output: [0,1]
Explanation:

Query Path Edge Weights Total Path Weight Half Explanation Answer
[1, 0] 1 → 0 [7] 7 3.5 Sum from 1 → 0 = 7 >= 3.5, median is node 0. 0
[0, 1] 0 → 1 [7] 7 3.5 Sum from 0 → 1 = 7 >= 3.5, median is node 1. 1
Example 2:
Input: n = 3, edges = [[0,1,2],[2,0,4]], queries = [[0,1],[2,0],[1,2]]
Output: [1,0,2]
Explanation:

Query Path Edge Weights Total Path Weight Half Explanation Answer
[0, 1] 0 → 1 [2] 2 1 Sum from 0 → 1 = 2 >= 1, median is node 1. 1
[2, 0] 2 → 0 [4] 4 2 Sum from 2 → 0 = 4 >= 2, median is node 0. 0
[1, 2] 1 → 0 → 2 [2, 4] 6 3 Sum from 1 → 0 = 2 = 3, median is node 2. 2
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:

Query Path Edge Weights Total Path Weight Half Explanation Answer
[3, 4] 3 → 1 → 0 → 2 → 4 [1, 2, 5, 3] 11 5.5 Sum from 3 → 1 = 1 = 5.5, median is node 2. 2
[1, 2] 1 → 0 → 2 [2, 5] 7 3.5 Sum from 1 → 0 = 2 = 3.5, median is node 2. 2
Constraints:
2 <= n <= 10^5edges.length == n - 1edges[i] == [u_i, v_i, w_i]0 <= u_i, v_i < n1 <= w_i <= 10^91 <= queries.length <= 10^5queries[j] == [u_j, v_j]0 <= u_j, v_j < n- The input is generated such that
edgesrepresents a valid tree.
Solution
Approach: LCA with Binary Lifting
Root the tree at node 0 and run a BFS to get each node's parent, depth, weighted distance from the root, and the binary lifting table f[i][j] (the 2^j-th ancestor of i).
For a query (u, v): if u == v the answer is u. Otherwise let x = lca(u, v) and W = dist[u] + dist[v] - 2 * dist[x] be the length of the path. The median is the first node on the path from u whose distance from u is at least W / 2; compare 2 * distance >= W to avoid fractions.
- If
2 * (dist[u] - dist[x]) >= W, the median is on the way up fromutox(includingx). Lift fromuas far as the distance stays below half, then take one more step to the parent. - Otherwise it is on the way down from
xtov(excludingx). Lift fromvto the highest node belowxwhose distance fromuis still at least half.
Complexity: O((n + q) log n) time and O(n log n) space.
from collections import deque
class Solution:
def findMedian(
self, n: int, edges: List[List[int]], queries: List[List[int]]
) -> List[int]:
m = n.bit_length()
g = [[] for _ in range(n)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
f = [[0] * m for _ in range(n)]
p = [0] * n
depth = [0] * n
dist = [0] * n
q = deque([0])
while q:
i = q.popleft()
f[i][0] = p[i]
for j in range(1, m):
f[i][j] = f[f[i][j - 1]][j - 1]
for j, w in g[i]:
if j != p[i]:
p[j] = i
depth[j] = depth[i] + 1
dist[j] = dist[i] + w
q.append(j)
ans = []
for u, v in queries:
if u == v:
ans.append(u)
continue
x, y = u, v
if depth[x] < depth[y]:
x, y = y, x
for j in range(m - 1, -1, -1):
if depth[x] - depth[y] >= (1 << j):
x = f[x][j]
for j in range(m - 1, -1, -1):
if f[x][j] != f[y][j]:
x, y = f[x][j], f[y][j]
if x != y:
x = p[x]
w = dist[u] + dist[v] - 2 * dist[x]
if 2 * (dist[u] - dist[x]) >= w:
cur = u
for j in range(m - 1, -1, -1):
k = f[cur][j]
if depth[k] >= depth[x] and 2 * (dist[u] - dist[k]) < w:
cur = k
ans.append(p[cur])
else:
cur = v
for j in range(m - 1, -1, -1):
k = f[cur][j]
if (
depth[k] > depth[x]
and 2 * (dist[u] + dist[k] - 2 * dist[x]) >= w
):
cur = k
ans.append(cur)
return ans