#3515

Shortest Path in a Weighted Tree

Hard
ArrayTreeDepth-First SearchBinary Indexed TreeSegment TreeTree TraversalSegment Tree
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(n)
💡

Intuition

Time O(log n)Space O(n)

Use an Euler tour to flatten the tree, allowing efficient updates and queries via a segment tree. This reduces the complexity of path calculations significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform an Euler tour to create a flattened representation of the tree and record edge weights.
  2. 2Step 2: Build a segment tree over the flattened array to support efficient updates and queries.
  3. 3Step 3: For each query, either update the segment tree or retrieve the distance using point queries.
solution.py37 lines
1class SegmentTree:
2    def __init__(self, data):
3        self.n = len(data)
4        self.tree = [0] * (2 * self.n)
5        for i in range(self.n): self.tree[self.n + i] = data[i]
6        for i in range(self.n - 1, 0, -1): self.tree[i] = self.tree[i * 2] + self.tree[i * 2 + 1]
7    def update(self, idx, value):
8        idx += self.n
9        self.tree[idx] = value
10        while idx > 1:
11            idx //= 2
12            self.tree[idx] = self.tree[idx * 2] + self.tree[idx * 2 + 1]
13    def query(self, left, right):
14        res = 0
15        left += self.n
16        right += self.n
17        while left < right:
18            if left % 2:
19                res += self.tree[left]
20                left += 1
21            if right % 2:
22                right -= 1
23                res += self.tree[right]
24            left //= 2
25            right //= 2
26        return res
27
28def shortest_path_optimal(n, edges, queries):
29    # Build the tree and perform Euler tour (not implemented)
30    segment_tree = SegmentTree([])  # Placeholder for segment tree initialization
31    results = []
32    for query in queries:
33        if query[0] == 1:
34            segment_tree.update(...)  # Update logic
35        elif query[0] == 2:
36            results.append(segment_tree.query(...))  # Query logic
37    return results

Complexity note: Segment tree operations (update and query) are O(log n), making the overall complexity efficient for multiple queries.

  • 1Euler tour helps flatten the tree.
  • 2Segment tree allows efficient updates and queries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.