BST Basics
What is a Binary Search Tree?
A Binary Search Tree (BST) is a fundamental data structure in computer science that provides an efficient way to store and retrieve sorted data. It is a binary tree with unique properties that enable fast search, insertion, and deletion operations.
Key Characteristics of BST
-
Node Structure: Each node in a BST contains:
- A key (or value)
- A left child reference
- A right child reference
-
Ordering Property:
- For any node, all keys in its left subtree are less than the node's key
- All keys in its right subtree are greater than the node's key
graph TD
A[8] --> B[3]
A --> C[10]
B --> D[1]
B --> E[6]
C --> F[14]
Basic Operations
1. Insertion
When inserting a new node, we compare its value with existing nodes to find the correct position.
public void insert(int key) {
root = insertRec(root, key);
}
private Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
2. Search
Searching in a BST is efficient with O(log n) time complexity in balanced trees.
public Node search(Node root, int key) {
if (root == null || root.key == key)
return root;
if (key < root.key)
return search(root.left, key);
return search(root.right, key);
}
3. Deletion
Deletion is more complex and involves three scenarios:
- Deleting a leaf node
- Deleting a node with one child
- Deleting a node with two children
Operation |
Average Case |
Worst Case |
Search |
O(log n) |
O(n) |
Insertion |
O(log n) |
O(n) |
Deletion |
O(log n) |
O(n) |
Challenges with BST
The performance of BST depends on its balance. An unbalanced tree can degrade to a linked list, causing O(n) time complexity for operations.
Why Balance Matters
In real-world applications like database indexing, search engines, and file systems, maintaining a balanced tree is crucial for optimal performance.
Learning with LabEx
At LabEx, we provide hands-on environments to practice and understand BST implementations and balancing techniques.