Design an iterator for a binary search tree (BST). The iterator will be initialized with the root node of the BST.
Each call to getNext()
should return the next smallest element in the BST in ascending order.
The iterator should provide a method hasMore()
to indicate if there are more elements to retrieve.
BSTIter iter = new BSTIter(root); iter.getNext(); // returns 4 iter.getNext(); // returns 8 iter.hasMore(); // returns true iter.getNext(); // returns 10 iter.hasMore(); // returns true iter.getNext(); // returns 16 iter.hasMore(); // returns true iter.getNext(); // returns 22 iter.hasMore(); // returns false
getNext()
and hasMore()
should operate on average in O(1) time complexity.getNext()
will only be called when there is a next smallest element available.