FastPrepDistance Between Two Tree Nodes

Distance Between Two Tree Nodes

Amazon logoAmazon● MediumFULLTIMEPHONE SCREENONSITE INTERVIEW

Problem statement

You are given a rooted tree whose nodes are numbered from 1 through treeNodes. The arrays treeFrom and treeTo describe the undirected edges of the tree, and root identifies its root.

Given two node IDs source and target, return the number of edges on the unique path between them.

The serialized edge list supplies the tree structure without parent pointers.

Function

distanceBetweenNodes(treeNodes: int, treeFrom: int[], treeTo: int[], root: int, source: int, target: int) → int

Examples

Example 1

treeNodes = 7treeFrom = [1,1,2,2,3,3]treeTo = [2,3,4,5,6,7]root = 1source = 4target = 7return = 4

The unique path is 4 -> 2 -> 1 -> 3 -> 7, which contains 4 edges.

Example 2

treeNodes = 5treeFrom = [1,1,3,3]treeTo = [2,3,4,5]root = 1source = 3target = 5return = 1

Node 5 is adjacent to node 3, so their distance is 1.

More Amazon problems

See Amazon hiring insights
Saved
public int distanceBetweenNodes(int treeNodes, int[] treeFrom, int[] treeTo, int root, int source, int target) {
  // write your code here
}
treeNodes7
treeFrom[1,1,2,2,3,3]
treeTo[2,3,4,5,6,7]
root1
source4
target7
expected4
Checking account…