Problem · Tree
Distance Between Two Tree Nodes
Learn this problemProblem 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) → intExamples
Example 1
treeNodes = 7treeFrom = [1,1,2,2,3,3]treeTo = [2,3,4,5,6,7]root = 1source = 4target = 7return = 4The 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 = 1Node 5 is adjacent to node 3, so their distance is 1.