Problem · Tree
Distance Between Two Tree Nodes
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 problem statement continues
ProExamples
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.
FastPrep Pro
Reported in 1 Amazon interview this weekUnlock this recently reported problem
FastPrep Pro gives you full access to interview problems reported within the last week.
- Full problem statement and constraints
- 1 more worked example, explained
- Guided hints and editorial
- Run your code on real test cases
$9/month
Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.
Free plan — 2 of 2 free unlocks used this week