A Binary Search Tree (BST) is a type of binary tree where each node has the following properties:
- Key Value Property:
- For any node
N
:- All values in the left subtree of
N
are less than the value ofN
. - All values in the right subtree of
N
are greater than the value ofN
.
- All values in the left subtree of
- For any node
- No Duplicates:
- Each value in the BST is unique.
Characteristics of BST
- Binary Structure: Each node can have at most two children: left and right.
- Sorted Order: An in-order traversal of a BST results in values being sorted in ascending order.
- Efficient Search: BST allows for fast searching, insertion, and deletion operations, with time complexity O(h)O(h), where hh is the height of the tree.
Basic Operations in BST
1. Search
To search for a value in a BST:
- Start at the root.
- Compare the value with the current node:
- If it matches, the search is successful.
- If it’s smaller, move to the left child.
- If it’s larger, move to the right child.
Algorithm:
2. Insertion
To insert a value into a BST:
- Start at the root and traverse to the appropriate leaf position based on the key value property.
- Insert the new value as a leaf node.
Algorithm:
3. Deletion
To delete a node:
- Locate the node to be deleted.
- Handle three cases:
- No Children: Remove the node.
- One Child: Replace the node with its child.
- Two Children: Replace the node with its in-order successor or predecessor.
Algorithm:
Advantages of BST
- Efficient Searches: Allows O(h)O(h) search, where hh is the tree height.
- Dynamic: BST can grow dynamically with insertions and deletions.
- In-Order Traversal: Provides sorted data effortlessly.
Limitations
- Unbalanced Trees: If the tree becomes skewed (e.g., inserting sorted data), operations can degrade to O(n)O(n).
- Height Dependency: Efficiency depends on the tree height.
Applications of BST
- Search Operations: Fast retrieval of data in dictionaries, phonebooks, and databases.
- Sorting: Use in-order traversal to retrieve sorted data.
- Range Queries: Efficiently find all values within a range.
Example Tree
For the values: [50, 30, 70, 20, 40, 60, 80]
- Structure:
A Binary Search Tree is a fundamental data structure that provides efficient data organization for many computational problems.