LeetCode #3515 — HARD

Shortest Path in a Weighted Tree

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer n and an undirected, weighted tree rooted at node 1 with n nodes numbered from 1 to n. This is represented by a 2D array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates an undirected edge from node ui to vi with weight wi.

You are also given a 2D integer array queries of length q, where each queries[i] is either:

  • [1, u, v, w']Update the weight of the edge between nodes u and v to w', where (u, v) is guaranteed to be an edge present in edges.
  • [2, x]Compute the shortest path distance from the root node 1 to node x.

Return an integer array answer, where answer[i] is the shortest path distance from node 1 to x for the ith query of [2, x].

Example 1:

Input: n = 2, edges = [[1,2,7]], queries = [[2,2],[1,1,2,4],[2,2]]

Output: [7,4]

Explanation:

  • Query [2,2]: The shortest path from root node 1 to node 2 is 7.
  • Query [1,1,2,4]: The weight of edge (1,2) changes from 7 to 4.
  • Query [2,2]: The shortest path from root node 1 to node 2 is 4.

Example 2:

Input: n = 3, edges = [[1,2,2],[1,3,4]], queries = [[2,1],[2,3],[1,1,3,7],[2,2],[2,3]]

Output: [0,4,2,7]

Explanation:

  • Query [2,1]: The shortest path from root node 1 to node 1 is 0.
  • Query [2,3]: The shortest path from root node 1 to node 3 is 4.
  • Query [1,1,3,7]: The weight of edge (1,3) changes from 4 to 7.
  • Query [2,2]: The shortest path from root node 1 to node 2 is 2.
  • Query [2,3]: The shortest path from root node 1 to node 3 is 7.

Example 3:

Input: n = 4, edges = [[1,2,2],[2,3,1],[3,4,5]], queries = [[2,4],[2,3],[1,2,3,3],[2,2],[2,3]]

Output: [8,3,2,5]

Explanation:

  • Query [2,4]: The shortest path from root node 1 to node 4 consists of edges (1,2), (2,3), and (3,4) with weights 2 + 1 + 5 = 8.
  • Query [2,3]: The shortest path from root node 1 to node 3 consists of edges (1,2) and (2,3) with weights 2 + 1 = 3.
  • Query [1,2,3,3]: The weight of edge (2,3) changes from 1 to 3.
  • Query [2,2]: The shortest path from root node 1 to node 2 is 2.
  • Query [2,3]: The shortest path from root node 1 to node 3 consists of edges (1,2) and (2,3) with updated weights 2 + 3 = 5.

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • edges[i] == [ui, vi, wi]
  • 1 <= ui, vi <= n
  • 1 <= wi <= 104
  • The input is generated such that edges represents a valid tree.
  • 1 <= queries.length == q <= 105
  • queries[i].length == 2 or 4
    • queries[i] == [1, u, v, w'] or,
    • queries[i] == [2, x]
    • 1 <= u, v, x <= n
    • (u, v) is always an edge from edges.
    • 1 <= w' <= 104
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer n and an undirected, weighted tree rooted at node 1 with n nodes numbered from 1 to n. This is represented by a 2D array edges of length n - 1, where edges[i] = [ui, vi, wi] indicates an undirected edge from node ui to vi with weight wi. You are also given a 2D integer array queries of length q, where each queries[i] is either: [1, u, v, w'] – Update the weight of the edge between nodes u and v to w', where (u, v) is guaranteed to be an edge present in edges. [2, x] – Compute the shortest path distance from the root node 1 to node x. Return an integer array answer, where answer[i] is the shortest path distance from node 1 to x for the ith query of [2, x].

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Tree · Segment Tree

Example 1

2
[[1,2,7]]
[[2,2],[1,1,2,4],[2,2]]

Example 2

3
[[1,2,2],[1,3,4]]
[[2,1],[2,3],[1,1,3,7],[2,2],[2,3]]

Example 3

4
[[1,2,2],[2,3,1],[3,4,5]]
[[2,4],[2,3],[1,2,3,3],[2,2],[2,3]]
Step 02

Core Insight

What unlocks the optimal approach

  • Use an Euler tour to flatten the tree into an array so each node’s subtree corresponds to a contiguous segment.
  • Build a segment tree over this Euler tour to support efficient range updates and point queries.
  • For an update query [1, <code>u</code>, <code>v</code>, <code>w'</code>], adjust the distance for all descendants by applying a delta update to the corresponding range in the flattened array.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3515: Shortest Path in a Weighted Tree
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3515: Shortest Path in a Weighted Tree
// package main
// 
// // https://space.bilibili.com/206214
// type fenwick []int
// 
// func newFenwickTree(n int) fenwick {
// 	return make(fenwick, n+1)
// }
// 
// // 把下标 i 的元素增加 val
// func (f fenwick) update(i, val int) {
// 	for ; i < len(f); i += i & -i {
// 		f[i] += val
// 	}
// }
// 
// // [1,i] 的元素和
// func (f fenwick) pre(i int) (s int) {
// 	for ; i > 0; i &= i - 1 {
// 		s += f[i]
// 	}
// 	return
// }
// 
// func treeQueries(n int, edges [][]int, queries [][]int) (ans []int) {
// 	g := make([][]int, n+1)
// 	for _, e := range edges {
// 		x, y := e[0], e[1]
// 		g[x] = append(g[x], y)
// 		g[y] = append(g[y], x)
// 	}
// 
// 	in := make([]int, n+1)
// 	out := make([]int, n+1)
// 	clock := 0
// 	var dfs func(int, int)
// 	dfs = func(x, fa int) {
// 		clock++
// 		in[x] = clock // 进来的时间
// 		for _, y := range g[x] {
// 			if y != fa {
// 				dfs(y, x)
// 			}
// 		}
// 		out[x] = clock // 离开的时间
// 	}
// 	dfs(1, 0)
// 
// 	// 对于一条边 x-y(y 是 x 的儿子),把边权保存在 weight[y] 中
// 	weight := make([]int, n+1)
// 	diff := newFenwickTree(n)
// 	update := func(x, y, w int) {
// 		// 保证 y 是 x 的儿子
// 		if in[x] > in[y] {
// 			y = x
// 		}
// 		d := w - weight[y] // 边权的增量
// 		weight[y] = w
// 		// 把子树 y 中的最短路长度都增加 d(用差分树状数组维护)
// 		diff.update(in[y], d)
// 		diff.update(out[y]+1, -d)
// 	}
// 
// 	for _, e := range edges {
// 		update(e[0], e[1], e[2])
// 	}
// 	for _, q := range queries {
// 		if q[0] == 1 {
// 			update(q[1], q[2], q[3])
// 		} else {
// 			ans = append(ans, diff.pre(in[q[1]]))
// 		}
// 	}
// 	return
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(h)

Approach Breakdown

LEVEL ORDER
O(n) time
O(n) space

BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.

DFS TRAVERSAL
O(n) time
O(h) space

Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.

Shortcut: Visit every node once → O(n) time. Recursion depth = tree height → O(h) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Forgetting null/base-case handling

Wrong move: Recursive traversal assumes children always exist.

Usually fails on: Leaf nodes throw errors or create wrong depth/path values.

Fix: Handle null/base cases before recursive transitions.