Solution: Closest Node to Path in Tree
Let’s solve the Closest Node to Path in Tree using the Tree Breadth-First Search pattern.
We'll cover the following
Statement
You are given a positive integer, n
, representing the number of nodes in a tree, numbered from edges
of length edges[i]
You are also given a 2D integer array query
of length query[i]
For each query i
, find the node on the path between
Return an integer array where the value at index
Note: If there are multiple such nodes at the same minimum distance, return the one with the smallest index.
Constraints:
n
edges.length
edges[i].length
query.length
query[i].length
The graph is a tree.
Solution
The solution’s essence lies in first determining the exact path between two nodes in a tree using breadth-first search (BFS), and then identifying which node along that path is closest to a third given node. To do this, we perform a second BFS from the third node to compute the shortest distance to all other nodes in the tree. Finally, by comparing these distances for each node on the path, we select the one with the minimum distance, breaking ties by choosing the smaller node index.
Using the intuition above, we implement the algorithm as follows:
Initialize a 2D array,
tree
, to store the given tree as an adjacency list to represent node connections.For each edge
[u, v]
inedges
, addv
totree[u]
andu
totree[v]
. This builds a bidirectional structure from the inputedges
.Initialize an array,
answer
, to store the answer to each query.For each query
[start, end, node]
:Use BFS to find the path from
start
toend
:Initialize an array,
parents
, of sizen
with all entries as-1
to keep track of each node’s parent.Create a queue and a
visited
array to perform standard BFS.Push
start
into the queue and mark it as visited.For every dequeued node:
If it equals
end
, break the loop.Otherwise, enqueue all unvisited neighbors, mark them visited in the
visited
array, and record their parent in theparents
array.
Reconstruct the path from
start
toend
:Starting from
end
, backtrack using theparents
array until reachingstart
.Collect all nodes along this path into a
path
array.Reverse the
path
to get the correct order fromstart
toend
.
Use BFS again to calculate the shortest distance from the
node
to all other nodes:Initialize a
dist
array of sizen
, all set to the maximum integer value.Set
dist[node] = 0
and start BFS fromnode
.For each dequeued node:
For all its unvisited neighbors (i.e.,
dist[v]
is still at maximum integer value), setdist[v] = dist[u] + 1
and enqueue them.
Identify the closest node on the path to
node
:Initialize
minDist
with the maximum integer value andanswerNode
with-1
.Traverse each node
p
in thepath
:If
dist[p]
is less thanminDist
, or if the distance is equal andp
is smaller thananswerNode
, update bothminDist
andanswerNode
.
Add
answerNode
to theanswer
array.
After processing all queries, return the
answer
array containing the closest node on each path.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.