binary-search-tree-iterator 1.0.0
Binary Search Tree Iterator
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <vector>
3#include <stack>
4
5using namespace std;
6
11{
12 int val;
15 TreeNode() : val(0), left(nullptr), right(nullptr) {}
16 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
18};
19
21{
22public:
23 vector<TreeNode*>* node_array;
25
27 {
28 stack<TreeNode*> node_stack;
29 TreeNode* current = root;
30 node_array = new vector<TreeNode*>{};
31
32 while (current != nullptr || !node_stack.empty())
33 {
34 while (current != nullptr)
35 {
36 node_stack.push(current);
37 current = current->left;
38 }
39 current = node_stack.top();
40 node_stack.pop();
41 node_array->push_back(current);
42 current = current->right;
43 }
44 }
45
47 {
48 if (node_array)
49 delete node_array;
50 }
51
52 int next()
53 {
54 if (!node_array)
55 return -1; // no array code
56 int length = (int)node_array->size();
57 if (length <= 0)
58 return -2; // empty array code
59 if (current_index >= length)
60 current_index = 0; // rewind to beginning if domain is exceeded
61 return (*node_array)[current_index++]->val; // return current value and increment
62 }
63
64 bool hasNext()
65 {
66 return current_index < (int)node_array->size();
67 }
68};
69
71{
72 if (root == nullptr)
73 return;
74 delete_tree(root->left);
75 delete_tree(root->right);
76 delete root;
77}
78
79int main()
80{
81 TreeNode* root = new TreeNode(7, new TreeNode(3), new TreeNode(15, new TreeNode(9), new TreeNode(20)));
82 BSTIterator* obj = new BSTIterator(root);
83
84 int param_1 = obj->next();
85 cout << param_1 << " ";
86
87 param_1 = obj->next();
88 cout << param_1 << " ";
89
90 bool param_2 = obj->hasNext();
91 cout << param_2 << " ";
92
93 param_1 = obj->next();
94 cout << param_1 << " ";
95
96 param_2 = obj->hasNext();
97 cout << param_2 << " ";
98
99 param_1 = obj->next();
100 cout << param_1 << " ";
101
102 param_2 = obj->hasNext();
103 cout << param_2 << " ";
104
105 param_1 = obj->next();
106 cout << param_1 << " ";
107
108 param_2 = obj->hasNext();
109 cout << param_2 << endl;
110
111 delete_tree(root);
112 delete(obj);
113 return 0;
114}
int current_index
Definition main.cpp:24
bool hasNext()
Definition main.cpp:64
int next()
Definition main.cpp:52
BSTIterator(TreeNode *root)
Definition main.cpp:26
~BSTIterator()
Definition main.cpp:46
vector< TreeNode * > * node_array
Definition main.cpp:23
void delete_tree(TreeNode *root)
Definition main.cpp:70
int main()
Definition main.cpp:79
Definition for a binary tree node.
Definition main.cpp:11
int val
Definition main.cpp:12
TreeNode * left
Definition main.cpp:13
TreeNode(int x, TreeNode *left, TreeNode *right)
Definition main.cpp:17
TreeNode * right
Definition main.cpp:14
TreeNode(int x)
Definition main.cpp:16
TreeNode()
Definition main.cpp:15