binary-search-tree-iterator 1.0.0
Binary Search Tree Iterator
Loading...
Searching...
No Matches
BSTIterator Class Reference
Collaboration diagram for BSTIterator:

Public Member Functions

 BSTIterator (TreeNode *root)
 
 ~BSTIterator ()
 
int next ()
 
bool hasNext ()
 

Data Fields

vector< TreeNode * > * node_array
 
int current_index
 

Detailed Description

Definition at line 20 of file main.cpp.

Constructor & Destructor Documentation

◆ BSTIterator()

BSTIterator::BSTIterator ( TreeNode root)
inline

Definition at line 26 of file main.cpp.

26 : node_array(NULL), current_index(0)
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 }
int current_index
Definition main.cpp:24
vector< TreeNode * > * node_array
Definition main.cpp:23
Definition for a binary tree node.
Definition main.cpp:11
TreeNode * left
Definition main.cpp:13
TreeNode * right
Definition main.cpp:14

References TreeNode::left, node_array, and TreeNode::right.

◆ ~BSTIterator()

BSTIterator::~BSTIterator ( )
inline

Definition at line 46 of file main.cpp.

47 {
48 if (node_array)
49 delete node_array;
50 }

References node_array.

Member Function Documentation

◆ hasNext()

bool BSTIterator::hasNext ( )
inline

Definition at line 64 of file main.cpp.

65 {
66 return current_index < (int)node_array->size();
67 }

References current_index, and node_array.

Referenced by main().

◆ next()

int BSTIterator::next ( )
inline

Definition at line 52 of file main.cpp.

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 }

References current_index, and node_array.

Referenced by main().

Field Documentation

◆ current_index

int BSTIterator::current_index

Definition at line 24 of file main.cpp.

Referenced by hasNext(), and next().

◆ node_array

vector<TreeNode*>* BSTIterator::node_array

Definition at line 23 of file main.cpp.

Referenced by BSTIterator(), hasNext(), next(), and ~BSTIterator().


The documentation for this class was generated from the following file: