CodingReported in a candidate post, Aug 2018
Check if two nodes exist in the same path of a binary tree
Filed under Samsung
Free read 2 of 3Confirm if 'same path' means one must be an ancestor of the other from the root.
The question
Given a binary tree and two specific nodes, determine whether both nodes lie on the exact same root-to-leaf path.
Constraints
- Nodes are given as references or pointers.
- All node values are unique.
Examples
- Input
- Tree: 1->2->3, Nodes: 1 and 3
- Output
- True
- Why
- Node 1 is the root and node 3 is a child of 2, lying on the path 1 -> 2 -> 3.
Approach
Confirm if 'same path' means one must be an ancestor of the other from the root.
Find the paths from root to both nodes using DFS and check if one path is a prefix of the other.
Find the Lowest Common Ancestor (LCA). If the LCA is equal to one of the two nodes, then they lie on the same path.
Nodes not present in the tree, or nodes being the same.
Tips
- What they are testing: Test when one node is an ancestor of the other vs when they diverge into different subtrees.
- Common mistake: Assuming that finding both nodes in the tree means they share a path without checking ancestry relationships.
Related Samsung questions
Collected from public candidate posts and coding forums. Updated Nov 2026.