Binary Search Tree
Binary Search Tree
June 2025
• Right Subtree: The value of every node in the right subtree is greater
than the value of the parent node.
• No duplicates: A valid BST does not contain duplicate values.
• Recursion: A BST can be represented recursively, where each subtree is
itself a BST.
1.2 Applications
• Searching for a value in logarithmic time.
1
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
2
root->left = insert(root->left, data); // Insert into the left subtree
} else {
root->right = insert(root->right, data); // Insert into the right subtree
}
3
postorder(root->left); // Visit left subtree
postorder(root->right); // Visit right subtree
cout << root->data << " "; // Visit root
}
4. If it has two children, replace the node’s value with its in-order succes-
sor/predecessor and recursively delete the successor/predecessor.
4
// Recur down the tree to find the node to be deleted
if (key < root->data) {
root->left = deleteNode(root->left, key); // Go left if key is smaller
} else if (key > root->data) {
root->right = deleteNode(root->right, key); // Go right if key is greater
} else {
// Node with only one child or no child
if (root->left == nullptr) {
Node* temp = root->right;
delete root; // Free the node
return temp;
} else if (root->right == nullptr) {
Node* temp = root->left;
delete root;
return temp;
}
return root;
}
5
inOrderTraversal(root->left, arr, index); // Traverse left subtree
arr[*index] = root->data; // Store node value
(*index)++;
inOrderTraversal(root->right, arr, index); // Traverse right subtree
}
}
// In-order traversal
cout << "In-order traversal: ";
inorder(root); // Should print 20 30 40 50 60 70 80
6
cout << endl;
// Delete a node
root = deleteNode(root, 20); // Delete node with no children
root = deleteNode(root, 30); // Delete node with one child
root = deleteNode(root, 50); // Delete node with two children
return 0;
}