This project implements a Binary Search Tree (BST) in C++. Binary trees are a fundamental data structure in computer science, providing efficient operations for the insertion, search, and removal of elements.
Represents a node in the binary tree.
- Attributes:
int data: Stores the node's value.TreeNode* left: Pointer to the left child.TreeNode* right: Pointer to the right child.
Manages the root of the binary tree.
- Attribute:
TreeNode* root: Pointer to the root of the tree.
Adds a new node to the tree. If the value already exists, the insertion is ignored to maintain the uniqueness of elements.
Removes a node from the tree. There are three cases to consider:
- Node with no children (leaf).
- Node with a single child.
- Node with two children: it is replaced by the smallest node in the right subtree.
Finds a node in the tree based on the provided value. Returns the found node or the closest node if the value does not exist.
- Inorder (
inorder): Traverses the tree in ascending order. - Preorder (
preorder): Visits the root before the children. - Postorder (
postorder): Visits the root after the children. - Levelorder (
levelorder): Traverses the tree level by level using a queue.
- Number of Nodes (
nodes): Returns the total number of nodes in the tree. - Number of Leaves (
leaves): Returns the number of leaves (nodes without children).
Displays the tree structure hierarchically, representing levels with hyphens.
Fills the tree with a predefined set of values to facilitate testing and demonstrations.
The menu function offers an interactive menu that allows the user to perform the following operations:
- Insert: Add a new value to the tree.
- Size: Display the number of nodes in the tree.
- Leaf Count: Show how many leaves are in the tree.
- Print: Display the tree structure.
- Remove: Delete a specific value from the tree.
- Generate: Populate the tree with default values.
- Inorder: Perform an inorder traversal.
- Preorder: Perform a preorder traversal.
- Postorder: Perform a postorder traversal.
- Levelorder: Perform a levelorder traversal.
- -1. Exit: Terminate the program.
This implementation provides a solid foundation for understanding and manipulating binary search trees in C++. It is an excellent tool for learning and can be expanded with additional features, such as tree balancing or more advanced visual representation.
- Compile:
g++ -o binarytree main.cpp