Modify Random Pointer in Binary Tree
Filed under Amazon
Free read 3 of 3Confirm the exact definition of a successor (typically descendant or nodes in path).
The question
In a binary tree where each node has an additional random pointer, modify the random pointer to NULL if it does not point to a successor (descendant or ancestor) of the node; otherwise, leave it untouched.
Constraints
- Nodes contain left, right, and random pointers.
- Tree can be of any structure.
Examples
- Input
- Node A has random pointer to Node B (which is its child).
- Output
- Random pointer remains pointing to Node B.
- Why
- Since B is a successor/descendant of A, the pointer is untouched.
Approach
Confirm the exact definition of a successor (typically descendant or nodes in path).
For each node, traverse its subtree to check if the random pointer target exists within it. O(n^2) time.
First pass: collect all valid successors or compute subtree membership hashes/sets. Second pass: validate each random pointer against the set in O(1) time per node.
Handle trees with null random pointers or single node trees.
Tips
- What they are testing: Test with random pointers pointing to unrelated nodes, self, or valid descendants.
- Common mistake: Failing to correctly define what constitutes a successor in the tree context.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.