Binary Search Tree (C++)
Loading...
Searching...
No Matches
BST Class Reference

Iterative binary search tree storing integer values. More...

#include <BST.h>

Public Member Functions

 BST ()
 Constructs an empty BST.
 ~BST ()
 Destroys the BST and frees all dynamically allocated nodes.
void insert (int value)
 Inserts a value into the BST.
bool search (int value) const
 Searches for a value in the BST.
void inorder () const
 Performs an inorder traversal of the tree.
void levelOrder () const
 Performs a level-order (breadth-first) traversal of the tree.
bool remove (int value)
 Removes a value from the BST if it exists.

Detailed Description

Iterative binary search tree storing integer values.

The BST class is an iterative, pointer-based binary search tree implementation using raw pointers and manual dynamic memory management. The BST owns all allocated nodes and is responsible for their cleanup through its destructor.

The BST class manages dynamically allocated Node objects, forming a binary search tree structure. All operations, including insert, search, delete, and traversal, are implemented iteratively to avoid recursion.

The tree maintains standard BST ordering properties:

  • Left subtree contains values less than the node.
  • Right subtree contains values greater than the node.
  • Duplicate values are ignored.

Memory Management: The BST owns all its nodes. The destructor invokes a private destroyTree() helper method, ensuring that all nodes are properly freed and preventing memory leaks.

See also
Node

Definition at line 50 of file BST.h.

Constructor & Destructor Documentation

◆ BST()

BST::BST ( )

Constructs an empty BST.

Initializes the BST root pointer to nullptr.

Definition at line 26 of file BST.cpp.

26: root(nullptr) {}

◆ ~BST()

BST::~BST ( )

Destroys the BST and frees all dynamically allocated nodes.

Calls destroyTree() to deallocate all nodes in the tree.

Definition at line 31 of file BST.cpp.

31 {
32 destroyTree();
33}

Member Function Documentation

◆ inorder()

void BST::inorder ( ) const

Performs an inorder traversal of the tree.

Prints node values in ascending order using an iterative traversal.

Traverses the tree in-order using an iterative approach.

Uses an explicit stack to traverse the tree without recursion and prints values in ascending order.

Definition at line 102 of file BST.cpp.

102 {
103 if (!root) return;
104
105 Stack s;
106 Node* current = root;
107
108 while (current || !s.isEmpty()) {
109 while (current) {
110 s.push(current);
111 current = current->getLeft();
112 }
113
114 current = s.pop();
115 std::cout << current->getValue() << " ";
116 current = current->getRight();
117 }
118
119 std::cout << std::endl;
120}
Node * getRight() const
Returns a pointer to the right child node.
Definition Node.cpp:52
Node * getLeft() const
Returns a pointer to the left child node.
Definition Node.cpp:39
int getValue() const
Returns the stored integer value.
Definition Node.cpp:25
Node * pop()
Removes and returns the node at the top of the stack.
Definition Stack.cpp:40
bool isEmpty() const
Checks whether the stack is empty.
Definition Stack.cpp:52
void push(Node *n)
Pushes a node onto the stack.
Definition Stack.cpp:31

◆ insert()

void BST::insert ( int value)

Inserts a value into the BST.

Parameters
valueThe integer value to insert.
Note
Duplicate values are ignored.

Iteratively inserts a value into the BST.

The tree is traversed from the root to locate the appropriate insertion point. Duplicate values are detected and ignored to preserve BST invariants.

Definition at line 41 of file BST.cpp.

41 {
42 Node* newNode = new Node(value);
43
44 // Special case: empty tree
45 if (!root) {
46 root = newNode;
47 return;
48 }
49
50 Node* current = root;
51 Node* parent = nullptr;
52
53 // Traverse the tree to find the insertion point
54 while (current) {
55 parent = current;
56
57 if (value < current->getValue())
58 current = current->getLeft();
59 else if (value > current->getValue())
60 current = current->getRight();
61 else {
62 // Duplicate value detected; discard new node
63 delete newNode;
64 return;
65 }
66 }
67
68 // Attach the new node to its parent
69 if (value < parent->getValue())
70 parent->setLeft(newNode);
71 else
72 parent->setRight(newNode);
73}
void setLeft(Node *left)
Sets the pointer to the left child node.
Definition Node.cpp:46
void setRight(Node *right)
Sets the pointer to the right child node.
Definition Node.cpp:59

◆ levelOrder()

void BST::levelOrder ( ) const

Performs a level-order (breadth-first) traversal of the tree.

Visits nodes level by level (breadth-first traversal).

Uses a queue to visit nodes level by level starting from the root.

Definition at line 127 of file BST.cpp.

127 {
128 if (!root) return;
129
130 Queue q;
131 q.enqueue(root);
132
133 while (!q.isEmpty()) {
134 Node* current = q.dequeue();
135 std::cout << current->getValue() << " ";
136
137 if (current->getLeft())
138 q.enqueue(current->getLeft());
139 if (current->getRight())
140 q.enqueue(current->getRight());
141 }
142
143 std::cout << std::endl;
144}
Node * dequeue()
Removes and returns the node at the front of the queue.
Definition Queue.cpp:45
void enqueue(Node *n)
Adds a node to the end of the queue.
Definition Queue.cpp:31
bool isEmpty() const
Checks whether the queue is empty.
Definition Queue.cpp:58

◆ remove()

bool BST::remove ( int value)

Removes a value from the BST if it exists.

Parameters
valueThe value to remove.
Returns
true if the value was found and removed; otherwise false.

Deletes the specified value if it exists in the BST.

Handles all three standard BST deletion cases:

  1. Node is a leaf
  2. Node has one child
  3. Node has two children (using inorder successor replacement)

Definition at line 154 of file BST.cpp.

154 {
155 Node* parent = nullptr;
156 Node* current = root;
157
158 // Locate the node to delete
159 while (current && current->getValue() != value) {
160 parent = current;
161 if (value < current->getValue())
162 current = current->getLeft();
163 else
164 current = current->getRight();
165 }
166
167 if (!current)
168 return false; // Value not found
169
170 // ------------------------------------------------------------
171 // Case 1: Node has no children (leaf)
172 // ------------------------------------------------------------
173 if (!current->getLeft() && !current->getRight()) {
174 if (current == root)
175 root = nullptr;
176 else if (parent->getLeft() == current)
177 parent->setLeft(nullptr);
178 else
179 parent->setRight(nullptr);
180
181 delete current;
182 }
183
184 // ------------------------------------------------------------
185 // Case 2: Node has exactly one child
186 // ------------------------------------------------------------
187 else if (!current->getLeft() || !current->getRight()) {
188 Node* child = current->getLeft()
189 ? current->getLeft()
190 : current->getRight();
191
192 if (current == root)
193 root = child;
194 else if (parent->getLeft() == current)
195 parent->setLeft(child);
196 else
197 parent->setRight(child);
198
199 delete current;
200 }
201
202 // ------------------------------------------------------------
203 // Case 3: Node has two children
204 // ------------------------------------------------------------
205 else {
206 // Find inorder successor (leftmost node in right subtree)
207 Node* succParent = current;
208 Node* successor = current->getRight();
209
210 while (successor->getLeft()) {
211 succParent = successor;
212 successor = successor->getLeft();
213 }
214
215 // Replace current node's value with successor's value
216 current->setValue(successor->getValue());
217
218 // Remove successor node (which has at most one child)
219 Node* child = successor->getRight();
220
221 if (succParent->getLeft() == successor)
222 succParent->setLeft(child);
223 else
224 succParent->setRight(child);
225
226 delete successor;
227 }
228
229 return true;
230}
void setValue(int value)
Sets the stored integer value.
Definition Node.cpp:32

◆ search()

bool BST::search ( int value) const

Searches for a value in the BST.

Parameters
valueThe value to search for.
Returns
true if the value exists in the tree; otherwise false.

Iteratively searches for a value in the BST.

Traverses the tree according to BST ordering rules until the value is found or a null pointer is reached.

Definition at line 81 of file BST.cpp.

81 {
82 Node* current = root;
83
84 while (current) {
85 if (value == current->getValue())
86 return true;
87 else if (value < current->getValue())
88 current = current->getLeft();
89 else
90 current = current->getRight();
91 }
92
93 return false;
94}

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