A Binary Search Tree (BST) is a type of binary tree where each node follows these rules:
This property makes BSTs highly efficient for searching, insertion, and deletion operations, which are typically faster than operations on other data structures like arrays or linked lists.
A node in a BST has the following:
Example of a BST:
50
/ \
30 70
/ \ / \
20 40 60 80
To find a value in a BST:
C++ Implementation:
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
};
bool search(TreeNode* root, int key) {
if (root == nullptr) return false; // Key not found
if (root->data == key) return true; // Key found
if (key < root->data)
return search(root->left, key); // Search in left subtree
else
return search(root->right, key); // Search in right subtree
}
To insert a new value in a BST:
C++ Implementation:
TreeNode* insert(TreeNode* root, int value) {
if (root == nullptr) return new TreeNode(value); // Create a new node
if (value < root->data)
root->left = insert(root->left, value); // Insert in left subtree
else if (value > root->data)
root->right = insert(root->right, value); // Insert in right subtree
return root;
}
Deleting a node in a BST has three cases:
C++ Implementation:
TreeNode* findMin(TreeNode* root) {
while (root->left != nullptr) root = root->left;
return root; // Smallest node in the right subtree
}
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == nullptr) return root;
if (key < root->data)
root->left = deleteNode(root->left, key); // Search in left subtree
else if (key > root->data)
root->right = deleteNode(root->right, key); // Search in right subtree
else {
// Node with only one child or no child
if (root->left == nullptr) {
TreeNode* temp = root->right;
delete root;
return temp;
} else if (root->right == nullptr) {
TreeNode* temp = root->left;
delete root;
return temp;
}
// Node with two children
TreeNode* temp = findMin(root->right); // Inorder successor
root->data = temp->data; // Replace with successor's value
root->right = deleteNode(root->right, temp->data); // Delete successor
}
return root;
}
BSTs can be traversed using Inorder, Preorder, or Postorder traversals.
50, 30, 70, 20, 40, 60, 80.Steps:
50 → Root node.30 → Goes to left of 50.70 → Goes to right of 50.20 → Goes to left of 30.40 → Goes to right of 30.60 → Goes to left of 70.80 → Goes to right of 70.Resulting Tree:
50
/ \
30 70
/ \ / \
20 40 60 80
Inorder Traversal Output: 20 30 40 50 60 70 80
Preorder Traversal Output: 50 30 20 40 70 60 80
Postorder Traversal Output: 20 40 30 60 80 70 50
Open this section to load past papers