Closest Node to Path in Tree - Problem
Imagine you're building a GPS navigation system for a tree-structured network where locations are connected by bidirectional roads, forming a perfect tree (no cycles, exactly n-1 edges for n nodes).
You're given:
- n nodes numbered from 0 to n-1
- edges array defining the tree structure
- Multiple queries, each asking: "On the path from point A to point B, which location is closest to point C?"
For each query [start, end, target], you need to find the node on the unique path from start to end that has the minimum distance to the target node.
Goal: Return an array where each element is the closest node on the respective query path.
Input & Output
example_1.py β Basic Tree
$
Input:
n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[5,0],[6,0]], queries = [[5,3,4],[5,3,6]]
βΊ
Output:
[0, 0]
π‘ Note:
For query [5,3,4]: Path from 5 to 3 is [5,0,1,3]. Distances: 5β4 is 3, 0β4 is 1, 1β4 is 2, 3β4 is 2. Node 0 has minimum distance 1. For query [5,3,6]: Same path [5,0,1,3]. Distances: 5β6 is 2, 0β6 is 1, 1β6 is 2, 3β6 is 3. Node 0 has minimum distance 1.
example_2.py β Linear Tree
$
Input:
n = 4, edges = [[0,1],[1,2],[2,3]], queries = [[0,3,1]]
βΊ
Output:
[1]
π‘ Note:
For query [0,3,1]: Path from 0 to 3 is [0,1,2,3]. Distances: 0β1 is 1, 1β1 is 0, 2β1 is 1, 3β1 is 2. Node 1 has minimum distance 0.
example_3.py β Single Node Path
$
Input:
n = 3, edges = [[0,1],[1,2]], queries = [[1,1,0]]
βΊ
Output:
[1]
π‘ Note:
For query [1,1,0]: Path from 1 to 1 is just [1]. Distance 1β0 is 1. So node 1 is the answer.
Visualization
Tap to expand
Understanding the Visualization
1
Build Trail Map
Create the tree structure representing trail connections between lodges and camps
2
Query Processing
For each query 'find closest point to C on trail AβB', locate the unique path
3
Distance Calculation
Check every point on the AβB trail and measure hiking distance to destination C
4
Optimal Meeting Point
Return the trail point with minimum hiking distance to the target location
Key Takeaway
π― Key Insight: In a tree, there's exactly one path between any two nodes. We find this path and check the distance from each path node to our target, returning the node with minimum distance.
Time & Space Complexity
Time Complexity
O(m * nΒ²)
For m queries, each query requires O(n) to find path and O(nΒ²) to calculate distances
β Quadratic Growth
Space Complexity
O(n)
Space for BFS queue and storing paths
β‘ Linearithmic Space
Constraints
- 2 β€ n β€ 105
- edges.length == n - 1
- edges[i].length == 2
- 0 β€ node1i, node2i β€ n - 1
- The input represents a valid tree
- 1 β€ queries.length β€ 105
- query[i].length == 3
- 0 β€ starti, endi, nodei β€ n - 1
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code