Closest Node to Path in Tree

Try to solve the Closest Node to Path in Tree problem.

Statement

You are given a positive integer, n, representing the number of nodes in a tree, numbered from 00 to n1n-1. You are also given a 2D integer array edges of length n1n-1, where edges[i] =[ui,vi]= [u_i, v_i] indicates that there is a bidirectional edge connecting nodes uiu_i and viv_i.

You are also given a 2D integer array query of length mm, where query[i] =[starti,endi,nodei]= [start_i, end_i, node_i].

For each query i, find the node on the path between startistart_i and endiend_i that is closest to nodeinode_i in terms of the number of edges.

Return an integer array where the value at index ii corresponds to the answer for the ithi^{th} query.

Note: If there are multiple such nodes at the same minimum distance, return the one with the smallest index.

Constraints:

  • 11 \leq n 1000\leq 1000

  • edges.length ==n1== n - 1

  • edges[i].length ==2== 2

  • 0ui,vin10 \leq u_i, v_i \leq n-1

  • ui !=viu_i \space != v_i

  • 11 \leq query.length 1000\leq 1000

  • query[i].length ==3== 3

  • 0starti,endi,nodein10 \leq start_i, end_i, node_i \leq n-1

  • The graph is a tree.

Examples

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.