Implement an iterator over a binary search tree (BST). Your iterator is initialized with the root node of a BST.
next() Calling would 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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
It is required to implement a tree that can return the minimum value of BST because it requires only O (1) complexity to take the minimum each time, it is not possible to find the minimum value each time for the BST traversal. The Hasnext () and next () that can use the queue to store the results of BST in the queue when the constructor is in the queues are based on the status of the queue as follows:
public class Bstiterator { queue<treenode> res=new linkedlist<treenode> (); Public bstiterator (TreeNode root) { inistack (root); } /** @return Whether we have a next smallest number * /public boolean hasnext () { return!res.isempty (); } /** @return The next smallest number */public int Next () { return Res.poll (). Val ; public void Inistack (TreeNode root) { if (root==null) return; Inistack (root.left); Res.offer (root); Inistack (root.right); } }
Java-binary Search Tree Iterator