At first, I didn't know what the problem meant, and it was easy to know what he meant to say.
Idea: Find the minimum value, you can refer to the middle sequence traversal, with the help of stacks! Each element pops up, adding elements to the stack without having to traverse the entire tree immediately!
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class bstiterator {private: stack<treenode*> stk;public: bstiterator (TreeNode *root) {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*temp=stk.top (); Stk.pop (); int res=temp->val; temp=temp->right; while (temp) { Stk.push (temp); temp=temp->left; } return res; }};/ * * Your Bstiterator'll be a called like this: * bstiterator i = bstiterator (root); * while (I.hasnext ()) cout << i.next (); */
Binary Search Tree Iterator