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.
The idea of middle sequence traversal.
Using the stack to save the path from the root to the leftmost leaf node, the top node of the stack is the smallest node, each time it takes next, it takes the top node of the stack, and then puts the remaining nodes to the left-most leaf node path into the stack.
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class bstiterator {public:stack<treenode*> Stk; Bstiterator (TreeNode *root) {while (!stk.empty ()) Stk.pop (), while (root) {Stk.push (root); root = Root->left;} } /** @return Whether we have a next smallest number * /bool Hasnext () {return!stk.empty (); } /** @return The next smallest number */ int Next () {treenode* tmp = Stk.top (); int res = TMP->VAL;STK.POP (); tmp = t Mp->right;while (TMP) {Stk.push (TMP); tmp = Tmp->left;} return res; }};/ * * Your Bstiterator'll be a called like this: * bstiterator i = bstiterator (root); * while (I.hasnext ()) cout << i.next (); */
Leetcode:binary Search Tree Iterator