Skip to content
Concept ยท Data Structures and Algorithms

Binary Search Tree: Insertion, Deletion and Traversal, With Python Code You Can Run

Younus FardeenBy Younus FardeenUpdated 1 Dec 202610 min read
Short answer

A binary search tree (BST) is a binary tree where every key in a node's left subtree is smaller and every key in its right subtree is larger. That rule lets search, insert and delete skip half the tree at each step: O(log n) when balanced, O(n) when the tree degenerates into a chain.

On this pageBST vs binary tree: what the extra rule buysInsert and searchDeleting a node: the three casesWhy a BST can be slow: degenerate and balanced treesBST or something else? A decision tableFrequently asked questions

This page is for learners who already know what a tree is and now need the binary search tree in detail: how insertion, search and the three deletion cases work, what each traversal returns, and why a BST can be fast or useless depending on the order of input. The tree page covers vocabulary and the traversal table, so this page goes deeper into operations instead of repeating it.

All code ran on Python 3.9 on 1 December 2026 and the output shown is the real output. Complexity figures are the standard ones given on Wikipedia's BST page.

BST vs binary tree: what the extra rule buys

A binary tree only says each node has at most two children. A binary search tree adds an ordering rule: for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger. A binary tree with the same keys in any order is not a BST unless it obeys that rule.

Binary treeBinary search tree
Children per nodeAt most 2At most 2
Ordering ruleNoneLeft < node < right, for the whole subtree
Search for a keyVisit every node, O(n)Follow one path, O(height)
Inorder traversal givesNo useful orderKeys in sorted order
DuplicatesAllowedPolicy needed: reject, count, or send to one side
Typical useExpression trees, heapsOrdered sets and maps, range queries

The words "for the whole subtree" matter. A common mistake is to check only that each node is between its direct children. Here is a tree where every parent looks fine locally but 12 sits in the left subtree of 10:

def is_bst(node, lo=float("-inf"), hi=float("inf")):
    if node is None:
        return True
    key, left, right = node
    return lo < key < hi and is_bst(left, lo, key) and is_bst(right, key, hi)

# tuples are (key, left, right)
good = (10, (5, None, None), (15, None, None))
trap = (10, (5, None, (12, None, None)), (15, None, None))   # 12 is under 5 but bigger than 10
print("good:", is_bst(good))
print("trap:", is_bst(trap))

Output:

good: True
trap: False

The fix is to pass down a valid range (lo, hi) as the recursion goes deeper. This is the standard approach to the Validate BST interview problem listed at the end of the page.

Insertion follows the search path until it finds an empty spot, then puts the new node there. Search follows the same path and stops when the key matches or the path runs out. Below, the keys 50, 30, 70, 20, 40, 60, 80, 35 are inserted in that order, then the three depth-first traversals and two searches run.

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

def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)      # equal keys are ignored here
    return root

def search(root, key):
    while root and root.key != key:
        root = root.left if key < root.key else root.right
    return root is not None

def inorder(r):   return inorder(r.left) + [r.key] + inorder(r.right) if r else []
def preorder(r):  return [r.key] + preorder(r.left) + preorder(r.right) if r else []
def postorder(r): return postorder(r.left) + postorder(r.right) + [r.key] if r else []

root = None
for k in [50, 30, 70, 20, 40, 60, 80, 35]:
    root = insert(root, k)

print("inorder   ", inorder(root))
print("preorder  ", preorder(root))
print("postorder ", postorder(root))
print("search 60:", search(root, 60), "| search 65:", search(root, 65))

Output:

inorder    [20, 30, 35, 40, 50, 60, 70, 80]
preorder   [50, 30, 20, 40, 35, 70, 60, 80]
postorder  [20, 35, 40, 30, 60, 80, 70, 50]
search 60: True | search 65: False

Inorder printed the keys sorted, which is the property to remember: reading a BST left, node, right is a free sort. Preorder starts with the root, so it can rebuild the same tree if you insert the keys in that order. Postorder ends with the root and visits children first, which is why it is used to delete or free a tree. Each traversal touches every node once, so all three are O(n). For breadth-first (level order) traversal and the queue it needs, see BFS vs DFS.

Duplicate keys

The code above ignores a key that already exists. Real code has to choose: ignore it, store a count in the node, or always send equal keys to one side. Pick one rule and apply it everywhere, otherwise search and delete disagree.

Deleting a node: the three cases

Deletion is the operation interviewers ask about, because the shape of the tree decides what to do. First find the node, then handle one of three cases.

CaseSituationWhat to do
1Leaf (no children)Remove it: the parent's pointer becomes empty
2One childReplace the node with its only child
3Two childrenCopy the inorder successor (smallest key in the right subtree) into this node, then delete that successor from the right subtree

The inorder predecessor (largest key in the left subtree) works equally well. Either one keeps the ordering rule because it is the key closest in value to the one removed. The successor always has no left child, so deleting it falls back to case 1 or case 2. The code below deletes a leaf (20), a node with one child (40, whose only child is 35) and the root with two children (50).

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

def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
    return root

def inorder(r):
    return inorder(r.left) + [r.key] + inorder(r.right) if r else []

def delete(root, key):
    if root is None:
        return None
    if key < root.key:
        root.left = delete(root.left, key)
    elif key > root.key:
        root.right = delete(root.right, key)
    else:
        if root.left is None:            # case 1 (leaf) and case 2 (one child, right)
            return root.right
        if root.right is None:           # case 2 (one child, left)
            return root.left
        succ = root.right                # case 3: two children -> inorder successor
        while succ.left:
            succ = succ.left
        root.key = succ.key              # copy successor's key up
        root.right = delete(root.right, succ.key)   # remove the successor node
    return root

root = None
for k in [50, 30, 70, 20, 40, 60, 80, 35]:
    root = insert(root, k)

for k in [20, 40, 50]:                   # leaf, one child (35 under it), two children
    root = delete(root, k)
    print("after deleting", k, "->", inorder(root), "| root is", root.key)

Output:

after deleting 20 -> [30, 35, 40, 50, 60, 70, 80] | root is 50
after deleting 40 -> [30, 35, 50, 60, 70, 80] | root is 50
after deleting 50 -> [30, 35, 60, 70, 80] | root is 60

In the last line the root changed from 50 to 60: 60 was the smallest key in the right subtree, so it replaced the root and its old node was removed. The list stays sorted after every delete, which is a quick test for your own implementation.

Why a BST can be slow: degenerate and balanced trees

Search, insert and delete all cost O(height). If keys arrive already sorted, every key goes to the right and the tree becomes a linked list with height n - 1. The test inserts the numbers 1 to 100 two ways.

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

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

def height(r):
    return -1 if r is None else 1 + max(height(r.left), height(r.right))

def build(keys):
    root = None
    for k in keys:
        root = insert(root, k)
    return root

def middle_first(lo, hi, out):
    if lo > hi:
        return
    mid = (lo + hi) // 2
    out.append(mid)
    middle_first(lo, mid - 1, out)
    middle_first(mid + 1, hi, out)

n = 100
order = []
middle_first(1, n, order)
print("sorted input  height:", height(build(range(1, n + 1))))
print("middle-first  height:", height(build(order)))

Output:

sorted input  height: 99
middle-first  height: 6

Same hundred keys, height 99 against 6. A self-balancing BST avoids this by rotating nodes after inserts and deletes so the height stays O(log n). The two you will meet are the AVL tree, which keeps the subtree heights of every node within one of each other, and the red-black tree, which relaxes the balance slightly for cheaper updates. This page does not implement them: rotations are a separate topic, and in practice you use a library. Python has no built-in balanced tree, so people use a dict, a sorted list with the bisect module (see binary search), or a third-party package.

OperationAverage (random order)Worst case (sorted input)AVL or red-black
SearchO(log n)O(n)O(log n)
InsertO(log n)O(n)O(log n)
DeleteO(log n)O(n)O(log n)
Inorder traversalO(n)O(n)O(n)
SpaceO(n)O(n)O(n)

For how to read these notations, see time complexity and Big O. One more practical limit: the recursive code above uses one stack frame per level, so a 5,000-level chain would hit Python's default recursion limit of about 1,000. Balanced trees do not have this problem.

BST or something else? A decision table

You needUseWhy
Lookup by key onlyHash map (hashmap explained)O(1) average, no order needed
Keys in sorted order, range queries, floor and ceilingBalanced BST (Java TreeMap, C++ std::map)Ordered traversal and O(log n) updates
Always the smallest or largest itemHeapCheaper than a full ordering
Prefix lookups on stringsTrieCost depends on word length, not item count
Millions of rows on diskB-tree (database index)Wide nodes mean few disk reads

Interview practice, in order: Search in a BST, Insert into a BST, Validate Binary Search Tree, Kth Smallest Element in a BST, Lowest Common Ancestor of a BST and Delete Node in a BST. Problem lists are on coding practice websites, and the wider list of question types is in DSA interview questions. The parent path is the DSA learning path.

Frequently asked questions

What is a binary search tree?

A binary search tree is a binary tree in which each node's left subtree holds smaller keys and its right subtree holds larger keys. Because of that rule you can search, insert and delete by following a single path from the root, which takes O(log n) time when the tree is balanced.

What is the difference between a binary tree and a binary search tree?

Both allow at most two children per node. Only the binary search tree enforces an order: left keys are smaller, right keys are larger. That order makes searching fast and makes inorder traversal return sorted keys, while a plain binary tree has neither property.

How do you delete a node from a binary search tree?

Find the node, then handle three cases. A leaf is simply removed. A node with one child is replaced by that child. A node with two children takes the key of its inorder successor, the smallest key in the right subtree, and that successor node is then deleted instead.

Which traversal gives sorted order in a BST?

Inorder traversal: visit the left subtree, then the node, then the right subtree. Because every left key is smaller and every right key is larger, the keys come out in ascending order. Preorder and postorder do not give sorted output.

What is the time complexity of a BST?

Search, insert and delete take O(h), where h is the height. That is O(log n) on average or when the tree is balanced, and O(n) when the tree is a chain, for example after inserting already sorted keys. Traversing every node is O(n).

Why do we need AVL and red-black trees?

A plain BST can become lopsided and slow. AVL and red-black trees rotate nodes after changes to keep the height proportional to log n, so every operation stays O(log n). Standard libraries such as Java's TreeMap rely on this kind of tree.

Can a BST have duplicate keys?

It can, but you must choose a policy: reject duplicates, store a count in the node, or always place equal keys on the same side. The textbook definition usually assumes distinct keys. Whatever you choose must be used by insert, search and delete alike.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Tree data structure

Binary trees, BST, traversals, height and balance with tested code

7 min read
Concept

Heap data structure

Min heap, max heap, heapify, heapq, top-k and merge k lists with real output

6 min read
Concept

Binary search

Iterative, recursive, bisect, pitfalls and binary search on the answer

7 min read