File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ #include " ../Header.h"
2+ #include " ../TreeNode.h"
3+ using namespace std ;
4+
5+ class BSTIterator {
6+ private:
7+ stack<TreeNode*> fathers;
8+ TreeNode *iterator;
9+ public:
10+ BSTIterator (TreeNode *root) {
11+ iterator = root;
12+ if (iterator) {
13+ while (iterator->left ) {
14+ fathers.push (iterator);
15+ iterator = iterator->left ;
16+ }
17+ }
18+ }
19+
20+ /* * @return whether we have a next smallest number */
21+ bool hasNext () {
22+ return iterator != nullptr ;
23+ }
24+
25+ /* * @return the next smallest number */
26+ int next () {
27+ int val = iterator->val ;
28+ if (iterator->right ) {
29+ iterator = iterator->right ;
30+ while (iterator->left ) {
31+ fathers.push (iterator);
32+ iterator = iterator->left ;
33+ }
34+ }
35+ else if (!fathers.empty ()) {
36+ iterator = fathers.top ();
37+ fathers.pop ();
38+ } else iterator = nullptr ;
39+ return val;
40+ }
41+ };
42+ int main (int argc, char const *argv[])
43+ {
44+
45+ return 0 ;
46+ }
You can’t perform that action at this time.
0 commit comments