Find path between two nodes in a binary tree
Problem: Find Path Between Two Nodes in a Binary Tree
Given a binary tree and two target nodes, a and b, return the simple path from a to b (inclusive) as an ordered list of node values.
- The path should list nodes in the order you would visit them when traveling from
atobalong parent/child links. - You may assume the tree nodes have fields like
val,left, andright.
Examples
Example 1
Tree:
1
/ \
2 3
Input: a = 2, b = 3
Output: [2, 1, 3]
Example 2
Tree:
1
/ \
2 3
/ \
6 5
/ \
7 8
Input: a = 3, b = 5
Output: [3, 1, 2, 5]
Requirements
- Define what your function receives for
aandb(e.g., node references/pointers, unique IDs, or values). - Handle cases where one node is the ancestor of the other.
- Clarify behavior if one or both targets are not present (e.g., return an empty list or throw an error).
Follow-ups
- Duplicate values: If the tree can contain duplicate values, how does your approach change? What should be used to identify
aandb? - BST variant: If the tree is a Binary Search Tree, what (if anything) changes in:
- the algorithm,
- and the time complexity (compared to a general binary tree)?
AI interview prep
Core dilemma
The central engineering conflict is efficiently locating two potentially distant nodes within a tree and reconstructing their unique path, which necessarily involves finding their Lowest Common Ancestor (LCA) without explicit parent pointers, while optimizing for time and space complexity.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Find path between two nodes in a binary tree
Problem: Find Path Between Two Nodes in a Binary Tree
Given a binary tree and two target nodes, a and b, return the simple path from a to b (inclusive) as an ordered list of node values.
- The path should list nodes in the order you would visit them when traveling from
atobalong parent/child links. - You may assume the tree nodes have fields like
val,left, andright.
Examples
Example 1
Tree:
1
/ \
2 3
Input: a = 2, b = 3
Output: [2, 1, 3]
Example 2
Tree:
1
/ \
2 3
/ \
6 5
/ \
7 8
Input: a = 3, b = 5
Output: [3, 1, 2, 5]
Requirements
- Define what your function receives for
aandb(e.g., node references/pointers, unique IDs, or values). - Handle cases where one node is the ancestor of the other.
- Clarify behavior if one or both targets are not present (e.g., return an empty list or throw an error).
Follow-ups
- Duplicate values: If the tree can contain duplicate values, how does your approach change? What should be used to identify
aandb? - BST variant: If the tree is a Binary Search Tree, what (if anything) changes in:
- the algorithm,
- and the time complexity (compared to a general binary tree)?