Question
Implement an iterator over a binary search tree (BST). Your iterator is initialized with the root node of a BST.
Calling would return the next smallest number in the next() BST.
Note: next() hasNext() and should run in average O (1) time and uses O (h) memory, where H is the height of the Tree.
Solution
When a problem relates to BST and sequence, we should think about in-order traversal of BST.
We find that the original codes of Binary Tree inorder traversal can is modified to fit following codes.
while (It.hasnext ()) { System.out.println (It.next ()); }
Note that before print, we need to the push nodes to stack first.
Inorder traversal time complexity is O (n), so for each next () step, average Time is O (1).
And the stack costs O (h) because we either goes down or pops a node and then goes down.
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten One Public classBstiterator { A PrivateStack<treenode>Stack; - PrivateTreeNode Current; - the Publicbstiterator (TreeNode root) { -stack =NewStack<treenode>(); -Current =Root; - while(Current! =NULL) { + Stack.push (current); -Current =Current.left; + } A at } - - /** @returnwhether we have a next smallest number*/ - Public BooleanHasnext () { - return(! Stack.empty () | | | current! =NULL); - } in - /** @returnThe next smallest number*/ to Public intNext () { + while(Current! =NULL) { - Stack.push (current); theCurrent =Current.left; * } $TreeNode tmp =Stack.pop ();Panax Notoginseng intresult =Tmp.val; -Current =Tmp.right; the returnresult; + } A } the + /** - * Your Bstiterator 'll be a called like this: $ * Bstiterator i = new Bstiterator (root); $ * while (I.hasnext ()) v[f ()] = I.next (); - */
Binary Search Tree Iterator Solution