-
Notifications
You must be signed in to change notification settings - Fork 0
/
173.hpp
53 lines (45 loc) · 1.03 KB
/
173.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#ifndef LEETCODE_173_HPP
#define LEETCODE_173_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
#include "../common/leetcode.hpp"
using namespace std;
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
TreeNode *node = root;
while (node != nullptr) {
path.push(node);
node = node->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !path.empty();
}
/** @return the next smallest number */
int next() {
auto t = path.top();
path.pop();
if (t->right != nullptr) {
path.push(t->right);
auto n = t->right->left;
while (n != nullptr) {
path.push(n);
n = n->left;
}
}
return t->val;
}
private:
stack<TreeNode *> path;
};
#endif //LEETCODE_173_HPP