0
0
Data Structures Theoryknowledge~6 mins

Insertion in BST in Data Structures Theory - Full Explanation

Choose your learning style9 modes available
Introduction
Imagine you have a collection of numbers and you want to keep them organized so you can find any number quickly. The problem is how to add a new number into this collection without losing the order that helps you find numbers fast.
Explanation
Binary Search Tree Structure
A binary search tree (BST) is a special kind of tree where each node has at most two children. The left child contains values smaller than the node, and the right child contains values larger than the node. This structure helps keep data sorted and easy to search.
BST keeps data sorted by placing smaller values to the left and larger values to the right.
Finding the Correct Position
To insert a new value, start at the root and compare the new value with the current node. If the new value is smaller, move to the left child; if larger or equal, move to the right child. Repeat this until you find an empty spot where the new value fits.
Insertion finds the right spot by comparing values and moving left or right accordingly.
Inserting the New Node
Once the correct empty position is found, place the new value there as a new node. This keeps the BST property intact, meaning the tree remains sorted and balanced for efficient searching.
The new value is added as a leaf node where the search ends.
Handling Duplicate Values
Some BSTs do not allow duplicate values, while others may store duplicates in a specific way, such as always going to the right subtree. The insertion method must handle duplicates based on the chosen rule.
Duplicate handling depends on the BST rules and affects where duplicates are inserted.
Real World Analogy

Imagine a librarian placing new books on a shelf sorted by title. To add a new book, the librarian starts at the beginning and moves left or right depending on whether the new title comes before or after the current book, until finding the right empty spot to place it.

Binary Search Tree Structure → Books arranged on a shelf with titles in alphabetical order
Finding the Correct Position → Librarian comparing new book title with existing books to find the right spot
Inserting the New Node → Placing the new book in the empty space found on the shelf
Handling Duplicate Values → Deciding where to put a book if another book has the same title
Diagram
Diagram
       ┌─────┐
       │  10 │
       ├─────┤
       │     │
       └─┬─┬─┘
         │ │
     ┌───┘ └───┐
     │         │
   ┌─┴─┐     ┌─┴─┐
   │ 5 │     │ 15│
   └───┘     └───┘

Insert 12:
Start at 1012 > 10, go right
At 1512 < 15, go left (empty)
Place 12 here.
This diagram shows a BST with nodes 10, 5, and 15, and the insertion path for the value 12.
Key Facts
Binary Search Tree (BST)A tree where each node's left child is smaller and right child is larger than the node.
InsertionAdding a new value by finding the correct empty spot following BST rules.
Leaf NodeA node with no children where new values are inserted.
Duplicate HandlingThe rule deciding where to place values equal to existing nodes.
Code Example
Data Structures Theory
class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BST:
    def __init__(self):
        self.root = None

    def insert(self, value):
        if self.root is None:
            self.root = Node(value)
            return
        current = self.root
        while True:
            if value < current.value:
                if current.left is None:
                    current.left = Node(value)
                    return
                current = current.left
            else:
                if current.right is None:
                    current.right = Node(value)
                    return
                current = current.right

    def inorder(self, node, result):
        if node:
            self.inorder(node.left, result)
            result.append(node.value)
            self.inorder(node.right, result)

bst = BST()
bst.insert(10)
bst.insert(5)
bst.insert(15)
bst.insert(12)
result = []
bst.inorder(bst.root, result)
print(result)
OutputSuccess
Common Confusions
Believing new values can be inserted anywhere in the tree.
Believing new values can be inserted anywhere in the tree. Insertion must follow BST rules by comparing values and moving left or right to keep the tree sorted.
Thinking duplicates are always allowed and placed randomly.
Thinking duplicates are always allowed and placed randomly. Duplicates are handled by specific rules, often placed consistently in one subtree or not allowed.
Summary
Insertion in a BST keeps the tree sorted by placing smaller values to the left and larger to the right.
The process finds the correct empty spot by comparing the new value with existing nodes from the root down.
Handling duplicates depends on specific rules and affects where equal values are inserted.