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.
Analyse:inorder traversal of BST.
Runtime:28ms.
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classBstiterator { One Public: ABstiterator (TreeNode *root) { - inorder (root); - } the - /** @return Whether we have a next smallest number*/ - BOOLHasnext () { - return!qu.empty (); + } - + /** @return The next smallest number*/ A intNext () { at intNextsmallest =Qu.front (); - Qu.pop (); - returnnextsmallest; - } - Private: -queue<int>Qu; in - voidInorder (treenode*root) { to if(!root)return; + -Inorder (root->Left ); theQu.push (root->val); *Inorder (root->Right ); $ }Panax Notoginseng }; - the /** + * Your Bstiterator 'll be a called like this: A * Bstiterator i = bstiterator (root); the * while (I.hasnext ()) cout << i.next (); + */
Binary Search Tree Iterator