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.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classBstiterator {vector<int>v; intPos; Public: Bstiterator (TreeNode*root) {POS=0; Stack<TreeNode*>s; TreeNode*p = root, *pre =NULL; while(P | |!S.empty ()) { while(P) {S.push (P); P= p->Left ; } if(!S.empty ()) {P=S.top (); S.pop (); V.push_back (P-val); P= p->Right ; } } } /** @return Whether we have a next smallest number*/ BOOLHasnext () {returnPOS <v.size (); } /** @return The next smallest number*/ intNext () {returnv[pos++]; }};/** * Your bstiterator'll be called like this: * bstiterator i = bstiterator (root), * while (I.hasnext ()) cout <&L T I.next (); */
173. Binary Search Tree Iterator-iterators