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.
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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code