Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
+1 vote
606 views
in Information Technology by (178k points)
Explore the power of Binary Search Trees (BST) with our comprehensive guide. Learn the fundamentals, operations, and applications of BSTs. Discover efficient searching and sorting techniques using this popular data structure. Dive into key topics such as insertion, deletion, and traversal. Elevate your understanding of algorithms and optimize your coding skills with our in-depth Binary Search Tree introduction.

Please log in or register to answer this question.

3 Answers

0 votes
by (178k points)
edited by

Binary Search Tree (BST)

1. Introduction to Binary Search Tree

  • A Binary Search Tree is a binary tree data structure in which each node has at most two children, referred to as the left child and the right child.
  • The key property of a BST is that for each node, all elements in its left subtree are less than the node's value, and all elements in its right subtree are greater.

Let's understand the concept of Binary search tree with an example.Let's understand the concept of Binary search tree with an example.

In the depicted diagram, the root node is 40, and the left subtree nodes are smaller while the right subtree nodes are greater, adhering to the binary search tree property. Additionally, the left child of the root node is greater than its left child and smaller than its right child, maintaining the binary search tree criteria. Consequently, the tree illustrated above is confirmed to be a binary search tree.

Now, consider altering the value of node 35 to 55 in the same tree and assess whether the modified structure still qualifies as a binary search tree.

In the given tree, the root node has a value of 40, which is greater than its left child (30) but smaller than the right child of 30 (55). As a result, the tree does not adhere to the Binary Search Tree property, making it unsuitable as a binary search tree.

2. Advantages of Binary Search Tree

  • Efficient searching: The structure of a BST allows for efficient search operations.
  • Easy to implement: The basic operations like insertion, deletion, and search are relatively straightforward.
  • Ordered storage: The elements are stored in a sorted order, making it easy to perform range-based queries.

3. Example of Creating a Binary Search Tree

  • Let's consider the following example to create a BST:
        5
       / \
      3   8
     / \ / \
    1  4 7  9
     

Let's illustrate the creation of a binary search tree using the following example data elements: 45, 15, 79, 90, 10, 55, 12, 20, 50.

To begin, we insert 45 as the root of the tree. Moving forward, for each subsequent element, we compare it to the current node. If the element is smaller, we insert it as the root of the left subtree; if larger, it becomes the root of the right subtree. This process continues until all elements are appropriately placed.

Now, let's delve into the step-by-step creation of the Binary Search Tree using the provided data elements, starting with the insertion of 45.

Proceeding to the second step involves inserting the value 15. Since 15 is smaller than 45, it is added as the root node of the left subtree.

Step 3 - Insert 79.

As 79 is greater than 45, so insert it as the root node of the right subtree.

Step 4 - Insert 90.

90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.

Step 5 - Insert 10.

10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

Step 6 - Insert 55.

55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of 79.

Step 7 - Insert 12.

12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right subtree of 10.

Step 8 - Insert 20.

20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of 15.

Step 9 - Insert 50.

50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree of 55.

The process of constructing a binary search tree has been finalized. Subsequently, let's explore the operations applicable to a binary search tree, including insertions, deletions, and searches. Now, let's delve into the intricacies of conducting a search operation on a binary search tree.

4. Searching in Binary Search Tree

  • Searching in a BST involves comparing the target value with the current node's value and deciding whether to continue the search in the left or right subtree.

Searching involves locating a specific element or node within a data structure. In a Binary Search Tree (BST), the search process is streamlined due to the specific ordering of elements. The steps for searching a node in a Binary Search Tree are as follows:

  1. Begin by comparing the element to be searched with the root element of the tree.
  2. If the root matches the target element, return the location of the node.
  3. If there is no match, check whether the target element is smaller than the root. If so, move to the left subtree.
  4. If the target element is larger than the root, move to the right subtree.
  5. Repeat the procedure recursively until a match is found.
  6. If the element is not found, return NULL.

Let's illustrate the searching process in a binary tree with an example. Consider the binary search tree formed above, and suppose we need to find the node with the value 20 in the tree.

Step 1:

Step 2:

Step 3:

5. Algorithm to Search an Element in Binary Search Tree

function searchBST(node, target):
    if node is null or node.value is equal to target:
        return node
    if target is less than node.value:
        return searchBST(node.left, target)
    else:
        return searchBST(node.right, target)
 

0 votes
by (178k points)

6. Deletion in Binary Search Tree

  • Deleting a node in a BST requires maintaining the BST property after removal. There are three cases to consider: a node with no children, a node with one child, and a node with two children.

When removing a node from a binary search tree (BST), it is crucial to ensure that the BST property is preserved. The deletion process involves addressing three possible scenarios:

  1. If the node to be deleted is a leaf node,
  2. If the node to be deleted has only one child, or
  3. If the node to be deleted has two children.

Let's delve into each of these situations:

Scenario 1: Deletion of a Leaf Node Deleting a leaf node in a BST is a straightforward process. In this case, the leaf node is replaced with NULL, and the allocated space is subsequently freed. For example, consider the deletion of node 90 in the illustration below. Since the node is a leaf, it is replaced with NULL, and the associated space is freed.

When the node to be deleted in a Binary Search Tree (BST) has only one child, the process involves replacing the target node with its child. Subsequently, the child node inherits the value to be deleted. Following this replacement, the child node is set to NULL, and the allocated memory is freed. This deletion method is illustrated in the accompanying image. Taking the example of deleting node 79, as it has only one child (55), the replacement involves assigning the child (55) to the position of the target node (79). The replaced node (79) becomes a leaf node and can then be effortlessly deleted.

When dealing with the deletion of a node in a Binary Search Tree (BST) and the node to be deleted has two children, the process becomes more intricate compared to the other cases. The following steps outline the procedure for handling such scenarios:

  1. Identify the inorder successor of the node to be deleted.
  2. Replace the node with its inorder successor iteratively until the target node is positioned at a leaf of the tree.
  3. Finally, replace the node with NULL and release the allocated memory.

The determination of the inorder successor is crucial, especially when the right child of the node is not empty. To obtain the inorder successor, find the minimum element in the right child of the node.

The deletion process for a node with two children is illustrated in the accompanying image. In this example, let's consider the deletion of node 45, which serves as the root node. Since the node to be deleted has two children, it is replaced with its inorder successor. Subsequently, node 45 is moved to a leaf position, facilitating its straightforward deletion.

In a Binary Search Tree (BST), the insertion of a new key always occurs at a leaf node. To insert an element, the process begins by searching from the root node. If the element to be inserted is less than the root node, the search continues in the left subtree for an empty location. Conversely, if the element is greater, the search proceeds in the right subtree. The insertion process mirrors the search operation, ensuring the left subtree remains smaller than the root, and the right subtree is larger than the root.

Now, let's explore the node insertion process in a BST through an illustrative example.

7. Insertion in Binary Search Tree

  • Inserting a node involves finding the correct position for the new node while maintaining the BST property.

8. Complexity of Binary Search Tree

8.1 Time Complexity

  • On average, search, insertion, and deletion operations in a balanced BST have a time complexity of O(log n), where n is the number of nodes.

8.2 Space Complexity

  • The space complexity is O(n), where n is the number of nodes. This is the space required for storing the tree structure.

9. Implementation of Binary Search Tree

  • Below is a simple implementation of a Binary Search Tree in Python:
class TreeNode:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def insert(root, key):
    if root is None:
        return TreeNode(key)
    else:
        if root.val < key:
            root.right = insert(root.right, key)
        else:
            root.left = insert(root.left, key)
    return root

def search(root, key):
    if root is None or root.val == key:
        return root
    if root.val < key:
        return search(root.right, key)
    return search(root.left, key)

# Example usage
root = None
keys = [5, 3, 8, 1, 4, 7, 9]

for key in keys:
    root = insert(root, key)

search_result = search(root, 7)
 

This example provides a detailed explanation of Binary Search Trees, including their structure, advantages, creation, searching, algorithms, deletion, insertion, and complexity analysis. The provided Python code demonstrates a basic implementation of a Binary Search Tree.

0 votes
by (178k points)

FAQs on Binary Search tree

Q: What is a Binary Search Tree (BST)?

A: A Binary Search Tree is a binary tree data structure in which each node has at most two children, referred to as the left child and the right child. The key property of a BST is that the value of each node in the left subtree is less than or equal to the node's value, and the value of each node in the right subtree is greater than or equal to the node's value.

Q: What is the significance of the Binary Search Tree property?

A: The BST property ensures efficient searching, insertion, and deletion operations. It allows for fast retrieval of data by eliminating half of the remaining nodes at each step, similar to the binary search algorithm.

Q: How is a Binary Search Tree different from a regular binary tree?

A: The key difference is the ordering of nodes in a BST. In a BST, for each node, all nodes in its left subtree have values less than or equal to its value, and all nodes in its right subtree have values greater than or equal to its value. This ordering property is not strictly enforced in a regular binary tree.

Q: What is the time complexity of searching in a Binary Search Tree?

A: In a balanced BST, the time complexity of searching is O(log n), where n is the number of nodes in the tree. However, in the worst case (for an unbalanced tree), the time complexity can be O(n), where n is the number of nodes.

Q: How do you insert a node into a Binary Search Tree?

A: To insert a node into a BST, you compare the value of the node to be inserted with the root node. If it is less than the root, you recursively insert it into the left subtree; if it is greater, you recursively insert it into the right subtree. Repeat this process until an appropriate empty position is found.

Q: What is the process for deleting a node in a Binary Search Tree?

A: Deleting a node from a BST involves three cases: a node with no children (leaf node), a node with one child, and a node with two children. The process is more involved for the last case, requiring either finding the node's in-order predecessor or in-order successor.

Q: How do you balance a Binary Search Tree?

A: Balancing a BST involves restructuring the tree to ensure that the heights of the left and right subtrees of any node differ by at most one. Common balancing algorithms include AVL trees and Red-Black trees.

Q: Can a Binary Search Tree contain duplicate values?

A: It depends on the specific implementation. In some implementations, duplicate values may be allowed, and they are either placed in a specific order (e.g., all duplicates to the right) or handled in a different manner.

Q: What are the advantages of using a Binary Search Tree?

A: BSTs offer efficient searching, insertion, and deletion operations when balanced. They are also easy to implement and can be used in various applications such as searching, sorting, and dynamic set operations.

Q: What are the potential challenges with Binary Search Trees?

A: Unbalanced trees can lead to degraded performance, resulting in worst-case time complexities for operations. Self-balancing BSTs, like AVL or Red-Black trees, address this issue but add complexity to the implementation. Additionally, handling duplicates and maintaining balance during dynamic operations can be challenging.

Important Interview Questions and Answers on Binary Search tree

Q: What is a Binary Search Tree (BST)?

A Binary Search Tree is a binary tree data structure where each node has at most two child nodes, usually referred to as the left child and the right child. The key property of a BST is that the key (value) of nodes in the left subtree is less than the key of the root, and the key of nodes in the right subtree is greater than the key of the root.

Q: How is a Binary Search Tree different from a Binary Tree?

In a Binary Search Tree, the key of each node is greater than or equal to the keys in its left subtree and less than or equal to the keys in its right subtree. In a general Binary Tree, there are no specific rules about the placement of keys.

Q: How do you insert a node into a Binary Search Tree?

Here is the code

class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

def insert_node(root, key):
    if not root:
        return TreeNode(key)
    
    if key < root.key:
        root.left = insert_node(root.left, key)
    elif key > root.key:
        root.right = insert_node(root.right, key)

    return root
 

Q: How do you perform an in-order traversal on a Binary Search Tree?

Here is the code

def inorder_traversal(root):
    if root:
        inorder_traversal(root.left)
        print(root.key, end=" ")
        inorder_traversal(root.right)

# Example usage:
# Assuming 'root' is the root of the Binary Search Tree
# inorder_traversal(root)
 

Q: How do you search for a key in a Binary Search Tree?

Here is the code

def search_key(root, key):
    if not root or root.key == key:
        return root

    if key < root.key:
        return search_key(root.left, key)
    else:
        return search_key(root.right, key)
 

Q: How do you delete a node from a Binary Search Tree?

Here is the code

def delete_node(root, key):
    if not root:
        return root

    if key < root.key:
        root.left = delete_node(root.left, key)
    elif key > root.key:
        root.right = delete_node(root.right, key)
    else:
        if not root.left:
            return root.right
        elif not root.right:
            return root.left

        root.key = find_min(root.right).key
        root.right = delete_node(root.right, root.key)

    return root

def find_min(node):
    while node.left:
        node = node.left
    return node

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...