Implement an iterator over a binary search tree (BST). Your iterator is initialized with the root node of a BST.
Calling next () 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.
Reference: Https://oj.leetcode.com/discuss/20001/my-solutions-in-3-languages-with-stack
Solution idea: Save all Left children starting from the root node with a stack, each time invoking Next () pops an element from the stack, and will repeat the same process with the right child of the node as the subtree of the root node.
The algorithm satisfies the spatial complexity of O (h) and the time complexity of hasnext () satisfies O (1), although the time complexity of next () is O (h), but the process of the algorithm is still worth learning.
The C + + code is implemented as follows:
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */Class Bstiterator {Private: Stack<treenode *> Nodestack;voidPushall (TreeNode *root) { for(TreeNode *node = root; Node! = nullptr; node = node->left) {Nodestack.push (node); } } Public:Bstiterator(TreeNode *root) {Pushall (root); }/** @return Whether we have a next smallest number * /BOOL Hasnext () {return!nodestack.empty (); }/** @return the next smallest number * * intNext () {TreeNode *node = Nodestack.top (); Nodestack.pop (); Pushall (Node->right);returnnode->val; }};/** * Your Bstiterator'll be a called like this: * bstiterator i = bstiterator (root), * while (I.hasnext ()) cout <& Lt I.next (); */
The time performance of the algorithm is as follows:
Leetcode[tree]: Binary Search Tree Iterator