Do you think IIT Guwahati certified course can help you in your career?
No
Introduction to Binary Search Tree(BST)
A Binary Search Tree (BST) is a specialized data structure used in computer science to organize and store data in a sorted manner. It follows the properties of a binary tree, where each node has at most two children. In a BST, the left subtree of a node contains values less than the node, while the right subtree contains values greater than the node. This hierarchical structure enables efficient searching, insertion, and deletion operations, making BSTs widely used in applications requiring fast data retrieval
What is Binary Search Tree?
A binary Search Tree is a classification of Trees in which every node in the tree can have at most two children, the left child, and the right child. The data of the right child and the left child must be greater and smaller than the data of the parent node, respectively.
Key Properties That Distinguish a Binary Search Tree from a Regular Binary Tree
The properties that separate a binary search tree from a regular binary tree:
Order Property: In a BST, for each node, the left subtree contains only nodes with keys less than the node's key, and the right subtree contains only nodes with keys greater than the node's key. This is not required for a regular binary tree.
No Duplicate Keys: Typically, BSTs do not allow duplicate keys. Each key must be unique and placed in a specific order as per the BST property. A regular binary tree can have duplicate keys.
Efficient Search Operations: Due to the ordered nature of a BST, search operations (as well as insertions and deletions) can be performed more efficiently, often in O(log n) time for balanced trees. Regular binary trees do not have this order, making search operations potentially less efficient, with a time complexity of O(n) in the worst case.
Lets us see an example of a binary search tree.
In this BST, we can observe that the left child of every node has a value less than its parent node, and the right child of every node has a value greater than its parent node.
Search Operation in Binary Search Tree
The search operation in a BST takes advantage of the tree's ordered structure. Starting at the root, the algorithm compares the target value to the current node's value. If they match, the search is successful. If the target is less than the current node's value, the algorithm recurses into the left subtree; if greater, it recurses into the right subtree. This process continues until the target is found or a leaf node is reached, indicating that the target is not in the tree.
Algorithm
Start at the root node.
If the root is None, the target is not in the tree.
Compare the target value with the value of the current node:
If equal, the target is found.
If less, move to the left child and repeat the process.
If greater, move to the right child and repeat the process.
If a leaf node is reached and the target is not found, the target is not in the tree.
Consider the following BST:
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
To search for the value 7:
Start at the root (8): 7 is less than 8, so move to the left child (3).
At node 3: 7 is greater than 3, so move to the right child (6).
At node 6: 7 is greater than 6, so move to the right child (7).
At node 7: 7 is equal to 7, so the target is found.
int target = 7; TreeNode* result = search(root, target); if (result != NULL) printf("Value %d found in the BST.\n", target); else printf("Value %d not found in the BST.\n", target);
int target = 7; TreeNode* result = search(root, target); if (result != nullptr) cout << "Value " << target << " found in the BST." << endl; else cout << "Value " << target << " not found in the BST." << endl;
return 0; }
You can also try this code with Online C++ Compiler
int target = 7; TreeNode result = tree.search(tree.root, target); if (result != null) System.out.println("Value " + target + " found in the BST."); else System.out.println("Value " + target + " not found in the BST."); } }
You can also try this code with Online Java Compiler
target = 7 result = search_bst(root, target) if result: print(f"Value {target} found in the BST.") else: print(f"Value {target} not found in the BST.")
You can also try this code with Online Python Compiler
This code defines a TreeNode class and two functions: search_bst for searching a value in a BST, and insert for inserting new values into the BST. The example usage demonstrates creating a BST and searching for a value within it.
Now let us understand the procedure to insert and delete a node into the Binary Search Tree.
Inserting a node into Binary Search Tree
Consider a Binary Search Tree ‘T’ and an arbitrary node ‘N’ having value stored as ‘Val’. Below is the procedure to insert the node ‘N’ into ‘T’.
First, we will compare the value ‘Val’ with the data stored in the root node.
If ‘Val’ is greater than the root node's value, we will move to its right subtree.
If ‘Val’ is smaller than the root node's value, we will move to its left subtree.
We will repeat the first to third step until the current root node does not have left and right subtree.
Now, if ‘Val’ is smaller than the value of the current root node, we will insert node ‘N’ as its left child.
Else if ‘Val’ is greater than the value of the current root node, we will insert node ‘N’ as its right child.
Now let us try inserting a node with ‘Val’ equal to 5 into the above tree.
Comparing the value ‘5’ from the value of the root and finding it to be greater, so moving to the right subtree.
Comparing the value ‘5’ from the value of the current root and finding it to be smaller, so moving to the left subtree.
Comparing the value ‘5’ from the value of the current root and finding it to be greater, so moving to the right subtree.
On finding the current root without any subtree, we will insert the node ‘N’ as the right child.
Deleting a node from a Binary Search Tree
Let us consider a Binary Search Tree ‘T’ and the node to be deleted as ‘N’. Deletion of a node can be classified based on the number of children of the node to be deleted.
1. ‘N’ has no children
When the node ‘N’ has no children, we can simply replace it will the null value. For Example, the node with the value as ‘8’ is to be removed in the tree below.
Simply the node with the value ‘8’ can be removed.
2. ‘N’ has one child
When the node ‘N’ has only one child, we can replace it with its only child. For Example, the node having the value as ‘4’ is removed in the below tree.
Simply the node with the value ‘4’ can be replaced with its only child, and then the replaced node will be removed.
3. ‘N’ has two children
When node ‘N’ has both children, we will need to determine the immediate predecessor. To find the immediate predecessor, we need to move to the left child of the node ‘N’ and then keep moving to the right child of the current node unless there is no right child. Then the node we have is the immediate predecessor.
Now this immediate predecessor can be replaced with the node ‘N’. And then, the replaced node can be removed with the first or second method defined above accordingly. For Example, the node with the value as ‘7’ is to be removed in the tree below.
We will have to find its immediate predecessor to replace it with. The node with the value ‘5’ is the immediate predecessor with the above algorithm.
The node ‘N’ will be replaced with the immediate predecessor.
And then, the replaced node will be removed.
Time complexity
The time complexity of operations in a binary search tree (BST) depends on the height of the tree.
Best Case: For a balanced tree, where the height is logarithmic with respect to the number of nodes, the time complexity for search, insert, and delete operations is O(log n).
Average Case: Similarly, for a reasonably balanced tree, the average time complexity remains O(log n).
Worst Case: In the worst case, where the BST becomes unbalanced (like a linked list), the height becomes linear, leading to a time complexity of O(n) for search, insert, and delete operations.
Space complexity
Space complexity is O(n) for storing n nodes, as each node requires additional memory for its value and pointers.
Implementation of Binary Search Tree
The provided code implements a binary search tree (BST) that allows insertion and searching of values.
Example: In the main function, we create a BST and insert the following values: 8, 3, 10, 1, 6, 4, 7, 14, and 13. The root of the tree starts as NULL. As we insert each value, the tree organizes itself according to BST properties: left child < Parent < Right child.
When searching for a value (in this case, 7), the program traverses the tree, comparing the target value with the current node's value and deciding whether to go left or right. If the target is found, a message is printed; otherwise, a message indicates that the value is not found.
This implementation efficiently maintains the structure of the BST and supports dynamic insertion and searching of values.
Applications of Binary Search Tree (BST)
A Binary Search Tree (BST) is a hierarchical data structure that maintains elements in a sorted manner, enabling efficient searching, insertion, and deletion operations. BSTs are widely used in various applications where quick lookup, ordering, and dynamic data management are required.
Applications of BST are:
Database Indexing: Used in databases for indexing to speed up search queries.
Searching Algorithms: Efficient for searching elements in log-time complexity.
Symbol Tables in Compilers: Helps store and retrieve identifiers, variables, and keywords quickly.
Autocorrect and Spell Checking: BST-based dictionaries allow fast lookup of words.
Network Routing Algorithms: Used in hierarchical data structures for optimized routing.
File System Organization: Helps maintain sorted files for efficient access.
Implementing Priority Queues: BST variations like AVL and Red-Black Trees support balanced priority queues.
Advantages and Disadvantages of Binary Search Tree (BST)
Advantages of Binary Search Tree (BST)
Efficient Searching: Provides O(logn)O(\log n)O(logn) time complexity in a balanced BST.
Dynamic Sorting: Keeps data in sorted order, enabling in-order traversal for ordered data retrieval.
Flexible Data Structure: Can handle dynamic data insertions and deletions efficiently.
Memory Efficient: Unlike arrays, it doesn’t require pre-allocation of memory, utilizing space dynamically.
Supports Various Operations: Enables efficient searching, insertion, deletion, and range queries.
Disadvantages of Binary Search Tree (BST)
Unbalanced Tree Problem: If not balanced (e.g., skewed tree), it degrades to O(n)O(n)O(n) search time.
More Complex Implementation: Requires careful handling of pointers and balancing conditions.
Not Ideal for Small Datasets: For small datasets, simpler structures like arrays or linked lists may be more efficient.
Performance Depends on Input: If elements are inserted in sorted order, it can become skewed, leading to inefficiencies.
Frequently Asked Questions
How many maximum children can each Binary Search Tree node have?
The Binary Search Tree node can have a maximum of two children. The children are called left and right children.
What is the method to find the immediate predecessor?
To find the immediate predecessor, we need to move to the left child of the node ‘N’ and then keep moving to the right child of the current node unless there is no right child. Then the node we have is the immediate predecessor.
What is a key in a binary search tree?
A key in a binary search tree is the value stored in a node, used to organize and compare nodes according to the tree's ordering properties, ensuring that left children are smaller and right children are larger.
Why is it called a binary search tree?
It is called a binary search tree because it combines the properties of a binary tree (each node has at most two children) with the ability to perform efficient search operations, due to its ordered structure.
What is the rule of a Binary Search Tree (BST)?
A Binary Search Tree (BST) follows the BST property:
For any node x, all nodes in its left subtree have keys less than x.
All nodes in its right subtree have keys greater than x.
This property ensures efficient searching, insertion, and deletion in O(log n) time for balanced BSTs
Conclusion
In the above article, we have learned about Binary Search Trees. Binary Search Trees (BSTs) are fundamental data structures that provide efficient means for data storage, retrieval, and management. By leveraging the ordered nature of BSTs, we can perform search, insert, and delete operations with optimal efficiency, making them a preferred choice for many applications.