Introduction
A Binary Search Tree (BST) is a node-based binary tree data structure that maintains its elements in sorted order, allowing for efficient insertion, deletion, and search operations.
BST Properties
For any node in a Binary Search Tree:
- All keys in the left subtree are less than the node's key
- All keys in the right subtree are greater than the node's key
- Both the left and right subtrees must also be binary search trees
Basic Operations
Search Operation
- Start at the root node
- Compare the target value with the current node's value
- If equal, return the node
- If less, search in the left subtree
- If greater, search in the right subtree
- Repeat until found or reach a null node
Insertion Operation
- Start at the root node
- Compare the new value with the current node's value
- If less, go to left child; if greater, go to right child
- When reaching a null position, insert the new node
- Maintain the BST property throughout
BST Visualization
Example of a balanced Binary Search Tree
Time Complexity
- Search: O(h) where h is the height of the tree
- Insertion: O(h)
- Deletion: O(h)
- In-order Traversal: O(n)
Note: In balanced BSTs, h = O(log n), making operations efficient.
Pros of BSTs
- Efficient searching compared to arrays and linked lists
- Flexible size - grows and shrinks dynamically
- Maintains data in sorted order without explicit sorting
- Supports range queries and ordered operations
Learn More
For more detailed information about Binary Search Trees, visit:
GeeksforGeeks - Binary Search Tree