Facebook | Onsite | Tree Iterator
Company: Meta
Role: e4
Interview Stage: Onsite
Location: unknown
Year: unknown
Original Post Content:
Question:
https://leetcode.com/problems/binary-search-tree-iterator
Follow-up 1:
Assume BSTIterator is a library class. You need to extend the functionality of this class by implementing 2 methods:public boolean hasPrev() { }/** Can only take 1 step back */public Integer prev() { }
Example: 7 / \ 3 15 / \ 9 20ExtendedBSTIterator it = new ExtendedBSTIterator(root);it.hasNext(); // trueit.next(); // 3it.next(); // 7it.next(); // 9it.next(); // 15it.hasPrev(); // trueit.prev(); // 9it.hasPrev(); // false bacause we can only move 1 step backit.next(); // 15it.next(); // 20it.hasNext(); // falseit.hasPrev(); // trueit.prev(); // 15it.hasNext(); // trueit.next(); // 20
There are basically 2 ways to do this: composition and inheritance. What are the advantages and disadvantages of one approach over the other?
Follow-up 2:
What if you can move k steps back?