leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0173.cpp (1093B)
0 // Naive approach using vector to precompute in-order traversal
2 class BSTIterator {
3 vector<int> vec;
4 int current = 0;
6 public:
7 BSTIterator(TreeNode *root) {
8 stack<TreeNode *> st;
9 while (true) {
10 while (root) {
11 st.push(root);
12 root = root->left;
13 }
14 if (st.empty()) break;
15 root = st.top();
16 st.pop();
17 vec.push_back(root->val);
18 root = root->right;
19 }
20 }
22 int next() { return vec[current++]; }
24 bool hasNext() { return current < vec.size(); }
25 };
27 // Compute in-order on the fly
29 class BSTIterator {
30 stack<TreeNode *> st;
32 void fill_stack(TreeNode *root) {
33 while (root) {
34 st.push(root);
35 root = root->left;
36 }
37 }
39 public:
40 BSTIterator(TreeNode *root) { fill_stack(root); }
42 int next() {
43 int val = st.top()->val;
44 TreeNode *root = st.top()->right;
45 st.pop();
46 fill_stack(root);
47 return val;
48 }
50 bool hasNext() { return !st.empty(); }
51 };