Professional Documents
Culture Documents
Interview Camp
Technique: Record and Move On
Level: Medium
Given a BST that can contain duplicate elements, find the first occurrence of a number N.
Questions to Clarify:
Q. If there is a duplicate element, will it be on the left or right side of an equal element?
A. It can be on either side.
Q. By first occurrence, you mean a node that would come first in an inorder traversal?
A. Yes, that is correct.
Solution:
We use the Record and Move On technique. This is very similar to the Record and Move On technique we
used in Binary Search.
The idea is that when we do a binary search, we are moving closer to our target element. If we find a
node equal to the target, we record it in a variable. We then continue our search on the left, because if
there is another equal node that came earlier, it will be on the left.
After we're done with our search, the variable will have the earliest occurrence of the target.
Follow Up Question: What if you wanted the last occurrence of target?
Pseudocode:
current = root
result = null
while current != null
if current > target
go left
else if current < target
go right
else
result = current
go left
Test Cases:
Edge Cases: empty tree
Base Cases: single node tree
Regular Cases: target not in tree, target occurs once, multiple times
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
/*
* Helper code. Implement only if the interviewer wants you to.
*/
public class Node {
Node left;
Node right;
int value;
public Node() {
super();
}
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
© 2017 Interview Camp (interviewcamp.io)