173. Binary Search Tree Iterator
Problem description:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Solution:
- we need to use O(1) time to find the smallest element, so we can use traverse the tree toward left, push the element into a stack, which will have the root in the bottom, smallest element(left most) element on the top.
- One thing to notice is that, when we call hasNext(), we need to check whether if the current pop out root has a right subtree.
For example:1
2
3
4
53
/ \
1 4
/ \
0 2
In above graph, we can see that 2
is smaller 3
. But we need to remember that we only push [3,1,0]
into the stack. If we did not check for 1's
right subtree, we will get an incorrect next smaller element.
1 | class BSTIterator: |
1 | /** |
reference: