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:

[2, 2]: The shortest path from root node 1 to node 2 is 7.[1, 1, 2, 4]: The weight of edge (1, 2) changes from 7 to 4.[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:

[2, 1]: The shortest path from root node 1 to node 1 is 0.[2, 3]: The shortest path from root node 1 to node 3 is 4.[1, 1, 3, 7]: The weight of edge (1, 3) changes from 4 to 7.[2, 2]: The shortest path from root node 1 to node 2 is 2.[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:

[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.[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.[1, 2, 3, 3]: The weight of edge (2, 3) changes from 1 to 3.[2, 2]: The shortest path from root node 1 to node 2 is 2.[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 <= 105edges.length == n - 1edges[i] == [ui, vi, wi]1 <= ui, vi <= n1 <= wi <= 104edges represents a valid tree.1 <= queries.length == q <= 105queries[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' <= 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the shortest path between two points in a weighted tree using brute force, we blindly explore every single possible route that connects the starting point to the destination.
Here's how the algorithm would work step-by-step:
def shortest_path_brute_force(adjacency_list, starting_node, target_node):
# We explore every branch recursively to find all possible routes to the destination
def explore_all_routes(current_node, destination_node, current_path, current_weight):
if current_node == destination_node:
return [(list(current_path), current_weight)]
completed_routes = []
for neighbor_node, edge_weight in adjacency_list.get(current_node, []):
if neighbor_node not in current_path:
current_path.append(neighbor_node)
branch_routes = explore_all_routes(
neighbor_node,
destination_node,
current_path,
current_weight + edge_weight
)
completed_routes.extend(branch_routes)
current_path.pop()
return completed_routes
initial_path = [starting_node]
all_possible_routes = explore_all_routes(starting_node, target_node, initial_path, 0)
# We ensure at least one valid route exists before attempting to compare distances
if not all_possible_routes:
return [], float('inf')
shortest_route = min(all_possible_routes, key=lambda route_tuple: route_tuple[1])
return shortest_routeTo find the shortest path between any two locations in a tree-like network, the optimal strategy takes advantage of the unique property that trees have only one single path connecting any pair of points. Instead of wandering through every possible branch, we can simply start at the origin location and follow the single, unambiguous route straight to the destination while adding up the lengths of the connections along the way.
Here's how the algorithm would work step-by-step:
def find_shortest_path_in_tree(adjacency_list, starting_node, destination_node):
# We utilize depth-first search to traverse the tree along its single unique path.
def traverse_tree_path(current_node, parent_node, current_distance):
if current_node == destination_node:
return current_distance
# Each neighboring branch is explored to find the continuation of the path.
for neighbor_node, edge_weight in adjacency_list[current_node]:
if neighbor_node != parent_node:
path_result = traverse_tree_path(neighbor_node, current_node, current_distance + edge_weight)
if path_result is not None:
return path_result
return None
# The traversal starts from the origin location without any prior distance accumulated.
return traverse_tree_path(starting_node, -1, 0)| Case | How to Handle |
|---|---|
| Single node tree with no edges and a query asking for the distance between the node and itself | Return zero as the distance since the start and end nodes are identical. |
| Line graph or degenerate tree resembling a linked list with maximum allowed nodes | Use binary lifting or Heavy-Light Decomposition to prevent recursion depth overflow and ensure logarithmic query time. |
| Star graph where a single central node is connected to all other nodes | Compute distances efficiently by utilizing the center node as an intermediate path point for all queries. |
| Very large edge weights causing integer overflow when summed along a long path | Use 64-bit integer types for distance accumulators to safely handle accumulated values. |
| Queries asking for the shortest path between the exact same node | Return zero immediately upon detecting that the source and target nodes are identical. |
| Disconnected graph provided instead of a valid tree structure | Validate the input graph structure beforehand and throw an exception or return a sentinel value for unreachable pairs. |
| Massive batch of queries on a static tree structure | Precompute depths and binary lifting ancestor tables during a single DFS preprocessing step to answer each query in logarithmic time. |