List the Nodes on the Path Between Two Nodes of a Binary Tree
SnowflakeSoftware Engineer · Technical ScreenLast updated
Given a binary tree stored as child-index arrays and two node indices, return the nodes on the unique path between them, from the first node to the second. It tests parent tracking, ancestor reasoning and handling cases where one node lies above the other.
Given a binary tree and two of its nodes, return the nodes on the path that connects them.
Function Signature
def path_between_nodes(left: list[int], right: list[int], u: int, v: int) -> list[int]:
Rules
- The tree has
nnodes numbered0ton - 1, and node0is the root.left[i]andright[i]are the indices of nodei's left and right children, or-1when that child is missing. - In a tree, exactly one path connects two nodes: the sequence of nodes from
utovin which every two consecutive nodes are a parent and its child, and no node appears twice. - Return the indices of the nodes on that path in order, starting with
uand ending withv. Ifu == v, return[u].
Constraints
1 <= n == len(left) == len(right) <= 10^5- Every child index is
-1or between1andn - 1, every node other than0is the child of exactly one node, and the links form a single binary tree rooted at node0. 0 <= u <= n - 1and0 <= v <= n - 1- The tree can be a single path, so its depth can reach
n.
Examples
All three examples use this tree, drawn with node indices:
left = [1, 3, -1, -1, 6, -1, -1]
right = [2, 4, 5, -1, -1, -1, -1]
0
/ \
1 2
/ \ \
3 4 5
/
6
Example 1
Input: left = [1, 3, -1, -1, 6, -1, -1], right = [2, 4, 5, -1, -1, -1, -1], u = 6, v = 5
Output: [6, 4, 1, 0, 2, 5]
The path climbs from node 6 to the root and then descends to node 5.
Example 2
Input: left = [1, 3, -1, -1, 6, -1, -1], right = [2, 4, 5, -1, -1, -1, -1], u = 3, v = 6
Output: [3, 1, 4, 6]
The path turns at node 1 and never reaches the root.
Example 3
Input: left = [1, 3, -1, -1, 6, -1, -1], right = [2, 4, 5, -1, -1, -1, -1], u = 0, v = 6
Output: [0, 1, 4, 6]
Node 0 is an ancestor of node 6, so the path only descends.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.