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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
This problem is mainly test binary tree in the middle sequence traversal of the non-recursive form, need to define a stack to assist, binary search tree's contribution rule is left < Root < Right, with the middle sequence traversal can be from small to large to remove all nodes. The code is as follows:
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classBstiterator { Public: Bstiterator (TreeNode*root) { while(Root) {s.push (root); Root= root->Left ; } } /** @return Whether we have a next smallest number*/ BOOLHasnext () {return!S.empty (); } /** @return The next smallest number*/ intNext () {TreeNode*n =S.top (); S.pop (); intres = n->Val; if(n->Right ) {N= n->Right ; while(n) {s.push (n); N= n->Left ; } } returnRes; }Private: Stack<TreeNode*>s;};/** * Your bstiterator'll be called like this: * bstiterator i = bstiterator (root), * while (I.hasnext ()) cout << ; I.next (); */
[Leetcode] Binary search Tree Iterator Two-fork searching trees iterator