Shortest Path in a Weighted Tree - Problem
Dynamic Tree Path Queries

You're managing a weighted tree network with n nodes numbered from 1 to n, rooted at node 1. The network is represented by an array edges where each edges[i] = [u_i, v_i, w_i] represents a bidirectional connection between nodes u_i and v_i with weight w_i.

You need to handle two types of dynamic queries:
โ€ข Type 1: [1, u, v, w'] - Update the weight of edge between nodes u and v to w'
โ€ข Type 2: [2, x] - Find the shortest path distance from root node 1 to node x

Goal: Return an array containing the shortest distances for all Type 2 queries, processed in order.

Since it's a tree, there's exactly one path between any two nodes, making each shortest path query deterministic but requiring efficient updates.

Input & Output

example_1.py โ€” Basic Tree Operations
$ Input: n = 4, edges = [[1,2,5], [2,3,2], [2,4,3]], queries = [[2,3], [1,2,3,6], [2,3], [2,4]]
โ€บ Output: [7, 8, 9]
๐Ÿ’ก Note: Initial tree: 1--(5)--2--(2)--3, 2--(3)--4. Query path 1โ†’3: 5+2=7. Update edge (2,3) to weight 6. Query path 1โ†’3: 5+6=11. Query path 1โ†’4: 5+3=8.
example_2.py โ€” Multiple Updates
$ Input: n = 3, edges = [[1,2,1], [2,3,2]], queries = [[2,3], [1,1,2,5], [2,3], [1,2,3,1], [2,3]]
โ€บ Output: [3, 7, 6]
๐Ÿ’ก Note: Path 1โ†’3 initially costs 1+2=3. After updating (1,2) to 5: cost becomes 5+2=7. After updating (2,3) to 1: cost becomes 5+1=6.
example_3.py โ€” Single Node Query
$ Input: n = 2, edges = [[1,2,10]], queries = [[2,1], [1,1,2,20], [2,1]]
โ€บ Output: [0, 0]
๐Ÿ’ก Note: Querying distance from root (node 1) to itself always returns 0, regardless of edge weight updates.

Constraints

Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen