0% completed
Binary Search Trees (BSTs) provide efficient operations for searching, inserting, and deleting elements while maintaining their sorted structure. Each of these operations leverages the BST property—where the left subtree contains values smaller than the node, and the right subtree contains values greater than the node.
In this lesson, we will cover the three primary operations on BSTs:
- Insertion - Adding a new node while maintaining the BST structure.
- Searching - Finding a node in the BST efficiently.
- Deletion - Removing a node while preserving BST properties.
Each operation follows a recursive approach, breaking down the problem into smaller subproblems, making traversal more structured. Let's explore each operation in detail.
1. BST Insertion
Insertion in a Binary Search Tree (BST) requires finding the correct position while maintaining the BST property. Starting from the root, we compare the new value with the current node. If the value is smaller, we move to the left subtree; if greater, we move to the right. Once an empty spot is found, the new node is inserted.
Step-by-Step Algorithm
- If the BST is empty, create a new node and set it as the root.
- Start at the root and compare the new value with the current node’s value:
- If the value is smaller, move to the left subtree.
- If the value is greater, move to the right subtree.
- Repeat recursively until we find an empty spot (
NULL
). - Insert the new node at the found position, maintaining the BST structure.
Time Complexity
- Best and Average Case: O(log n)
- Each step eliminates half the remaining elements, making it logarithmic.
- Worst Case (Skewed Tree): O(n)
- If the tree is completely unbalanced (like a linked list), insertion takes linear time.
Space Complexity
- O(h), where h is the height of the tree
- Recursive calls take stack space proportional to the tree height.
2. BST Searching
Searching in a BST efficiently finds a given value by leveraging the BST property. Like insertion, we start from the root and decide whether to move left or right based on comparisons.
Step-by-Step Algorithm
- If the BST is empty, return "Not Found."
- Start at the root and compare the search key with the current node’s value:
- If the key matches, return the node.
- If the key is smaller, move to the left subtree.
- If the key is greater, move to the right subtree.
- Repeat recursively until the value is found or the search ends at a
NULL
pointer.
Code
Time Complexity
- In a balanced BST, searching takes O(log n) because we eliminate half of the remaining elements at each step, similar to binary search.
- In the worst case (skewed tree), searching takes O(n) as we may have to traverse all nodes in a single branch.
- The best case is O(1) if the root contains the key.
Space Complexity
- Space Complexity is O(h) for recursive (O(log n) in balanced, O(n) in skewed BST).
3. BST Deletion
Deleting a node from a Binary Search Tree (BST) requires adjusting the tree structure while ensuring that the BST property remains intact. The complexity of deletion varies depending on the number of children the node has.
We need to handle three cases:
- Leaf Node (No Children): If the node is a leaf, it is simply removed from the tree.
- Node with One Child: If the node has only one child, we replace it with its child, bypassing the node.
- Node with Two Children: We replace the node's value with the inorder successor (smallest value in the right subtree) and then recursively delete the successor node.
By following these steps, we ensure the BST remains valid while removing the specified node.
Step-by-Step Algorithm
-
Handle the Base Case:
- If the tree is empty (
node == null
), returnnull
as there is nothing to delete.
- If the tree is empty (
-
Traverse the Tree to Find the Node to Delete:
- If the key to delete is smaller than the current node’s value (
key < node.val
), recursively search in the left subtree by callingdelete(node.left, key)
. - If the key is greater than the current node’s value (
key > node.val
), recursively search in the right subtree by callingdelete(node.right, key)
.
- If the key to delete is smaller than the current node’s value (
-
Node to be Deleted is Found:
- If
key == node.val
, proceed to handle the deletion cases.
- If
-
Case 1: Node Has No Left Child (Only Right Child or Leaf Node)
- If
node.left == null
, returnnode.right
, effectively removing the current node.
- If
-
Case 2: Node Has No Right Child (Only Left Child)
- If
node.right == null
, returnnode.left
, effectively removing the current node.
- If
-
Case 3: Node Has Two Children (Both Left and Right Exist)
- Find the inorder successor, which is the smallest node in the right subtree.
- Use the helper function
minValueNode(node.right)
to locate this successor. - Copy the inorder successor's value to the current node (
node.val = successor.val
). - Recursively delete the successor node from the right subtree using
delete(node.right, successor.val)
.
-
Return the Updated Node:
- After handling all cases, return the updated node to maintain the tree structure.
This algorithm ensures that the BST properties are preserved after deletion.
Code
Time Complexity
- O(log n) in a balanced BST because we eliminate half of the nodes at each step while traversing.
- O(n) in a skewed BST as we may need to traverse all nodes if the tree is unbalanced.
Space Complexity
- O(h) for recursive approach due to recursive calls up to the tree height (log n in balanced BST).
Issues with BSTs
Binary Search Trees (BSTs) have several issues and limitations that can affect their performance and efficiency in specific scenarios. Some of the key issues with BSTs include:
-
Unbalanced BSTs: BSTs can become unbalanced due to the order in which elements are inserted. The tree can degenerate into a linked list if elements are inserted in a sorted or nearly sorted order. Unbalanced BSTs lead to poor time complexities for searching, insertion, and deletion operations, becoming closer to linear time O(n) instead of the optimal logarithmic time O(log n).
Example: A BST with elements inserted in sorted order: 1, 2, 3, 4.
-
Degenerate Trees: Degenerate trees are extreme cases of unbalanced BSTs where each node has only one child, essentially forming a linked list. Degenerate trees result in very poor time complexities for all operations, rendering the advantages of using BSTs ineffective.
Example: A degenerate BST with elements inserted in descending order: 4, 3, 2, 1.
-
Performance Issues: Unbalanced and degenerate BSTs can lead to significantly degraded performance for common operations like searching, insertion, and deletion. In the worst-case scenario, when the tree is degenerate, these operations can take linear time O(n), negating the primary benefit of using a BST.
-
Complex Balancing: Ensuring a BST remains balanced after insertion and deletion requires complex balancing algorithms. While self-balancing BSTs like AVL trees and Red-Black trees exist, implementing and maintaining these balancing mechanisms adds overhead and complexity to the code.
-
Lack of Unique Keys: BSTs generally do not support duplicate keys. The behavior might vary depending on the implementation when attempting to insert a duplicate key. Some implementations might overwrite the existing value, while others might reject the insertion.
-
Memory Overhead: Each node in a BST requires additional memory for storing pointers to the left and right children. The memory overhead can become significant for large datasets, especially if the tree is poorly balanced.
-
Not Suitable for Dynamic Datasets: BSTs are not well-suited for datasets that frequently change in size. Insertions and deletions can lead to imbalanced trees, requiring additional balancing operations, which can be computationally expensive.
-
Limited Search Performance for Equal Keys: While BSTs provide efficient search times for unique keys, searching for the next greater or lesser element for equal keys requires additional operations and may be less efficient.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible