|
Binary Search Tree (C++)
|
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. | |
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:
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.
| BST::BST | ( | ) |
| BST::~BST | ( | ) |
| 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.
| void BST::insert | ( | int | value | ) |
Inserts a value into the BST.
| value | The integer value to insert. |
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.
| 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.
| bool BST::remove | ( | int | value | ) |
Removes a value from the BST if it exists.
| value | The value to remove. |
Deletes the specified value if it exists in the BST.
Handles all three standard BST deletion cases:
Definition at line 154 of file BST.cpp.
| bool BST::search | ( | int | value | ) | const |