-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
114 lines (94 loc) · 2.52 KB
/
main.cpp
File metadata and controls
114 lines (94 loc) · 2.52 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class BSTIterator
{
public:
vector<TreeNode*>* node_array;
int current_index;
BSTIterator(TreeNode* root) : node_array(NULL), current_index(0)
{
stack<TreeNode*> node_stack;
TreeNode* current = root;
node_array = new vector<TreeNode*>{};
while (current != nullptr || !node_stack.empty())
{
while (current != nullptr)
{
node_stack.push(current);
current = current->left;
}
current = node_stack.top();
node_stack.pop();
node_array->push_back(current);
current = current->right;
}
}
~BSTIterator()
{
if (node_array)
delete node_array;
}
int next()
{
if (!node_array)
return -1; // no array code
int length = (int)node_array->size();
if (length <= 0)
return -2; // empty array code
if (current_index >= length)
current_index = 0; // rewind to beginning if domain is exceeded
return (*node_array)[current_index++]->val; // return current value and increment
}
bool hasNext()
{
return current_index < (int)node_array->size();
}
};
void delete_tree(TreeNode* root)
{
if (root == nullptr)
return;
delete_tree(root->left);
delete_tree(root->right);
delete root;
}
int main()
{
TreeNode* root = new TreeNode(7, new TreeNode(3), new TreeNode(15, new TreeNode(9), new TreeNode(20)));
BSTIterator* obj = new BSTIterator(root);
int param_1 = obj->next();
cout << param_1 << " ";
param_1 = obj->next();
cout << param_1 << " ";
bool param_2 = obj->hasNext();
cout << param_2 << " ";
param_1 = obj->next();
cout << param_1 << " ";
param_2 = obj->hasNext();
cout << param_2 << " ";
param_1 = obj->next();
cout << param_1 << " ";
param_2 = obj->hasNext();
cout << param_2 << " ";
param_1 = obj->next();
cout << param_1 << " ";
param_2 = obj->hasNext();
cout << param_2 << endl;
delete_tree(root);
delete(obj);
return 0;
}