Binary Search Tree (C++)
Loading...
Searching...
No Matches
BinarySearchTree.cpp
Go to the documentation of this file.
1
33
34
35
36#include <iostream>
37#include <limits>
38#include "BST.h"
39
40void clearScreen() {
41 system("CLS"); // Windows console clear
42}
43
44void pauseForUser() {
45 std::cout << "\nPress Enter to continue...";
46
47 // Clear the input buffer.
48 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
49
50 std::cin.get();
51}
52
53int main() {
54 BST tree;
55 int choice = 0; // User's menu selection.
56
57 while (true) {
58 clearScreen();
59
60 std::cout << "--- Binary Search Tree Menu ---\n";
61 std::cout << "1. Insert a value\n";
62 std::cout << "2. Delete a value\n";
63 std::cout << "3. Search for a value\n";
64 std::cout << "4. Inorder traversal\n";
65 std::cout << "5. Level-order traversal\n";
66 std::cout << "6. Exit\n";
67 std::cout << "Enter your choice: ";
68 std::cin >> choice;
69
70 if (!std::cin) { // Handle non-numeric or otherwise invalid input.
71 std::cin.clear();
72 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
73 std::cout << "Invalid input.\n";
74 pauseForUser();
75 continue;
76 }
77
78 if (choice == 6) {
79 clearScreen();
80 std::cout << "Exiting program...\n";
81 break;
82 }
83
84 int value;
85
86 clearScreen(); // Clear before showing the operation output
87
88 // Process the user's menu selection.
89 switch (choice) {
90 case 1:
91 std::cout << "Enter value to insert: ";
92 std::cin >> value;
93 tree.insert(value); // Insert the value, ignoring duplicates.
94 std::cout << "Value inserted.\n";
95 break;
96
97 case 2:
98 std::cout << "Enter value to delete: ";
99 std::cin >> value;
100 if (tree.remove(value))
101 std::cout << "Value deleted.\n";
102 else
103 std::cout << "Value not found.\n";
104 break;
105
106 case 3:
107 std::cout << "Enter value to search for: ";
108 std::cin >> value;
109 if (tree.search(value))
110 std::cout << "Value found in the tree.\n";
111 else
112 std::cout << "Value NOT found.\n";
113 break;
114
115 case 4:
116 std::cout << "Inorder traversal:\n";
117 tree.inorder();
118 break;
119
120 case 5:
121 std::cout << "Level-order traversal:\n";
122 tree.levelOrder();
123 break;
124
125 default:
126 std::cout << "Invalid choice.\n";
127 }
128
129 pauseForUser();
130 }
131
132 return 0;
133}
Declaration of the BST (Binary Search Tree) class.
Iterative binary search tree storing integer values.
Definition BST.h:50
void levelOrder() const
Performs a level-order (breadth-first) traversal of the tree.
Definition BST.cpp:127
void inorder() const
Performs an inorder traversal of the tree.
Definition BST.cpp:102
void insert(int value)
Inserts a value into the BST.
Definition BST.cpp:41
bool remove(int value)
Removes a value from the BST if it exists.
Definition BST.cpp:154
bool search(int value) const
Searches for a value in the BST.
Definition BST.cpp:81