Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Data Structures

Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look

Emma's seven number cards stored as a binary search tree: smaller goes left, bigger goes right, so 60 is found in 3 looks instead of 6. Insert and search step by step, a million cards answered in 15 looks, and the sorted input that turns the tree into a stick.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Data Structures

What you will learn

  • Explain the binary search tree rule with the higher-or-lower guessing game
  • Insert values and search a tree by walking one path down
  • Say why a well-shaped tree needs about log n looks, and why sorted input turns it into a stick
  • Read a small Python Node and NumberTree with insert and contains

Before you start

  • Big-O: Reading Cost From Code
  • Recursion

Emma has a box of number cards: 50, 30, 70, 20, 40, 60 and 80. They arrive in no order at all. Jack asks: is 60 there? Checking card by card, 60 turns up on look number six. And 65? All seven looks, and still no.

We want every look to throw away half of the cards, so 60 is found in three looks and 65 is ruled out in three looks too. That's exactly what a binary search tree does.

Higher or lower

Think of the guessing game. Emma hides one card, and after every guess she only says "higher" or "lower".

  • Guess one is 50, right in the middle. "Higher!" So 20, 30 and 40 are out in one go.
  • Guess two is 70. "Lower!" So 80 is out too.
  • Guess three is 60. Yes. Three guesses, not seven.

Now draw the guesses as a map. 50 is at the top. Lower means go left, higher means go right. Store the cards like this map, and you have a binary search tree.

Emma's tree: 50 at the root, 30 left and 70 right, then 20 and 40 under 30, 60 and 80 under 70; the search for 60 goes right at 50, left at 70, and finds 60 in three looks 50 30 70 20 40 60 80 60 > 50: right 60 < 70: left smaller goes left bigger goes right
Seven cards in three levels. Searching for 60 takes three looks.

Insert, then search, step by step

Start with an empty tree and the seven cards waiting.

  1. 50 comes first. The tree is empty, so 50 becomes the root, the top card.
  2. 30 is smaller than 50, so go left. Left of 50 is empty, so 30 goes there.
  3. 70 is bigger, so it goes right of 50.
  4. 20: smaller, smaller, so left of 30.
  5. 40: smaller than 50, bigger than 30, so right of 30.
  6. 60 goes left of 70, and 80 goes right of 70.

Seven cards, just three levels. Now search for 60 from the root: bigger than 50, go right; smaller than 70, go left; equals 60, found after three looks. For 65: right at 50, left at 70, and at 60 it's bigger, but 60 has nothing on its right. So 65 isn't there, and you knew after three looks.

That empty spot is useful, too. It's the very spot where 65 would go if you inserted it. And one walk down answers more than yes or no: keep going left and you stop at the smallest card, 20; keep going right and you stop at the biggest, 80.

Why it's fast: each level doubles the room

Three levels hold seven cards, so the most you ever look at is three. Every new level doubles the room: 7 cards, then 15, then 31. Ten levels hold 1,023, and twenty levels hold over a million. So a well-shaped tree with a million cards needs at most about twenty looks. A plain list may need all one million. Each look goes one level down and throws away about half: that's O(log n).

Cards that arrive sorted

Same rule, but now the cards arrive already sorted: 10, 20, 30 up to 70. 10 becomes the root. 20 is bigger, so it goes right. 30 is bigger than both, so right again. Every card goes right. Seven cards, seven levels: the tree has become a stick.

Sorted input 10 to 70 makes a stick of seven levels needing seven looks for 70; the same cards inserted 40 first, then 20 and 60, make a short tree of three levels needing three looks sorted order: a stick 10 20 30 40 50 60 70 7 looks for 70 better order: short and wide 40 20 60 10 30 50 70 3 looks for 70
The shape depends on the order the cards arrive.

Searching for 70 now goes right, right, right all the way down: seven looks for seven cards. Every look threw away only one card, so it's no better than checking card by card. Put the same seven cards in a better order (40 first, then 20 and 60, then the rest) and the tree is short and wide again, three looks. Real software knows this: a balanced tree rebalances itself, turning a few cards around whenever one side grows too tall.

The code

Here's the small brick the tree is built from:

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None  # smaller values go here
        self.right = None  # bigger values go here

A new node starts with no children. Every node points to at most two others, which is why it's called a binary tree. The tree itself:

from node import Node


class NumberTree:
    def __init__(self):
        self.root = None
        self.looks = 0  # nodes checked by the last search

    def insert(self, value):
        self.root = self._insert(self.root, value)

    def _insert(self, node, value):
        if node is None:
            return Node(value)
        if value < node.value:
            node.left = self._insert(node.left, value)
        else:
            node.right = self._insert(node.right, value)
        return node

    def contains(self, value):
        self.looks = 0
        node = self.root
        while node is not None:
            self.looks += 1
            if value == node.value:
                return True
            node = (node.left if value < node.value
                    else node.right)
        return False

_insert asks: is this spot empty? Then the new card goes here. Otherwise smaller goes left and bigger goes right, and it calls itself on that side (that's recursion). contains walks down from the root, adding one to looks at every node, until it finds the value or reaches None. Insert and search ask the same question at every node: smaller or bigger?

from number_tree import NumberTree

tree = NumberTree()
cards = [50, 30, 70, 20, 40, 60, 80]
for card in cards:
    tree.insert(card)
print("Is 60 there? " + str(tree.contains(60)).lower()
      + ", looks: " + str(tree.looks))
print("Is 65 there? " + str(tree.contains(65)).lower()
      + ", looks: " + str(tree.looks))
Is 60 there? true, looks: 3
Is 65 there? false, looks: 3

A million cards

import random
from number_tree import NumberTree

for n in (100, 10_000, 1_000_000):
    cards = list(range(1, n + 1))
    random.Random(457).shuffle(cards)  # mixed up

    tree = NumberTree()
    for card in cards:
        tree.insert(card)
    tree.contains(n + 1)  # not there
    print(f"{n:9,d} cards: {tree.looks} looks to say no")
      100 cards: 6 looks to say no
   10,000 cards: 9 looks to say no
1,000,000 cards: 15 looks to say no

With a million shuffled cards, this tree says no after 15 looks. A list would check all one million.

And the stick, in code

from number_tree import NumberTree

tree = NumberTree()
for card in range(10, 71, 10):
    tree.insert(card)  # the cards arrive sorted
print("Is 70 there? " + str(tree.contains(70)).lower()
      + ", looks: " + str(tree.looks))
Is 70 there? true, looks: 7

The cost

OperationCostWhy
Insert (well-shaped tree)O(log n)one path down to the empty spot
Search (well-shaped tree)O(log n)each look throws away about half
Search a plain listO(n)card after card
Search after sorted insertsO(n)the tree is a stick

Where you meet search trees

  • Databases find a record fast with a tree cousin of this idea, so they don't read the whole table.
  • Many languages keep a sorted map or set as a search tree that levels itself.
  • Linux keeps the jobs waiting for the processor in a tree, so it can find the next one fast.
  • Range questions, like every price from 30 to 60: find 30, then walk on in order. Walking in order is the subject of tree traversals.

Try it yourself

Add a min method to NumberTree that keeps going left until there is no left child, and print the smallest card. You should get 20.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 7 of 21

Previous
Hash Tables: The Name Tells You Where to Look
Next post
Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

What a Data Structure Is, and How Memory Works

Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.

Arrays and Dynamic Arrays: Full? Get a Box Twice the Size

A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.

Linked Lists: A Chain of Clues, Built in Python

In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.

Stacks: Last In, First Out, With the Undo Button

A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.

On this page

  • Higher or lower
  • Insert, then search, step by step
  • Why it's fast: each level doubles the room
  • Cards that arrive sorted
  • The code
  • A million cards
  • And the stick, in code
  • The cost
  • Where you meet search trees
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.