Heavy-Light Decomposition - Problem
Implement heavy-light decomposition on a tree to answer path queries efficiently in O(log² n) time complexity.
Given a tree with n nodes, you need to:
1. Build the heavy-light decomposition structure
2. Handle path queries from node u to node v
3. Return the sum of values along the path
The tree is represented as an adjacency list where edges[i] = [parent, child] indicates an edge between parent and child nodes. Node values are given in the values array where values[i] is the value of node i.
Path Query: Find the sum of all node values from node u to node v in the tree.
Input & Output
Example 1 — Simple Path Query
$
Input:
edges = [[0,1],[1,2],[1,3],[3,4]], values = [1,2,3,4,5], u = 0, v = 4
›
Output:
12
💡 Note:
Path from node 0 to node 4: 0 → 1 → 3 → 4. Sum = values[0] + values[1] + values[3] + values[4] = 1 + 2 + 4 + 5 = 12
Example 2 — Different Path
$
Input:
edges = [[0,1],[1,2],[1,3]], values = [5,10,15,20], u = 2, v = 3
›
Output:
45
💡 Note:
Path from node 2 to node 3: 2 → 1 → 3. Sum = values[2] + values[1] + values[3] = 15 + 10 + 20 = 45
Example 3 — Single Node Path
$
Input:
edges = [[0,1],[1,2]], values = [7,8,9], u = 1, v = 1
›
Output:
8
💡 Note:
Path from node 1 to itself contains only node 1. Sum = values[1] = 8
Constraints
- 2 ≤ n ≤ 104
- edges.length = n - 1
- -106 ≤ values[i] ≤ 106
- 0 ≤ u, v < n
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code