Algorithms

Binary tree: two paths per node to find values faster

Cover of the article Binary tree: two paths per node to find values faster
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does a binary tree work?
  2. What is a binary search tree?
  3. Binary search tree in PHP, Python, C and Java
  4. Why is searching a tree fast?
  5. Where do trees show up in everyday life?
  6. Now it’s your turn!

Binary tree is a data structure in which each node holds a value and can have up to two children: one on the left and one on the right. It starts at a single node, called the root, and branches out downward.

In the article on the queue, the challenge was to create the peek method. The answer: it returns the value of the node at the front, without touching any reference. And if the queue is empty, it returns “nothing” (null in PHP, None in Python). That’s all! If you thought of something similar, you’re on the right track.

The list, the stack and the queue are structures “in a line”. Today the story changes, and you’ll see recursion shine, as I promised!

How does a binary tree work?

Think of a family tree drawn from top to bottom: at the top there’s one person, below her are her children, below each child are that child’s children, and so on. A binary tree follows the same idea, with one rule: each node has at most two children.

Family tree with Ana at the top, her children Bia and Caio below and the grandchildren Duda, Enzo and Fábio, with labels for root, left child, right child, subtree and leaf
Ana’s family has the shape of a binary tree: nobody has more than two children.

A few terms you’ll hear all the time:

  • Root: the node at the top, where everything starts.
  • Child: the node linked right below another one. Each node can have a left child and a right child.
  • Leaf: a node with no children.
  • Subtree: any node together with everything below it. Keep this in mind: every subtree is also a tree!

What is a binary search tree?

It’s a binary tree that follows an organizing rule: for any node, smaller values go to the left and larger values go to the right. Look at the tree that forms when we insert the values 50, 30, 70, 20, 40, 60 and 80, in that order:

Binary search tree with root 50, children 30 and 70 and leaves 20, 40, 60 and 80
Binary search tree formed by the values 50, 30, 70, 20, 40, 60 and 80.
ValuePath takenWhere it goes
50The tree is emptyBecomes the root
30Smaller than 50Left of 50
70Larger than 50Right of 50
20Smaller than 50, smaller than 30Left of 30
40Smaller than 50, larger than 30Right of 30
60Larger than 50, smaller than 70Left of 70
80Larger than 50, larger than 70Right of 70
Step by step insertion of each value into the tree.
See the animation of insertion and search in the tree
Animation of the insertion of the values 50, 30, 70, 20, 40, 60 and 80 into a binary search tree, followed by the search for the value 60
Each value goes down the tree comparing itself with the nodes on the way. At the end, the search for 60 follows the same rule.

Binary search tree in PHP, Python, C and Java

The code has two functions. The insert function goes down the tree comparing values until it finds an empty spot. The in-order traversal visits everything on the left first, then the node itself, and finally everything on the right. Here it is in PHP:

<?php

class Node
{
    public ?Node $left = null;
    public ?Node $right = null;

    public function __construct(public int $value)
    {
    }
}

function insert(?Node $node, int $value): Node
{
    if ($node === null) {
        return new Node($value); // found the empty spot: the node is born here
    }

    if ($value < $node->value) {
        $node->left = insert($node->left, $value);
    } else {
        $node->right = insert($node->right, $value);
    }

    return $node;
}

function inOrder(?Node $node): void
{
    if ($node === null) {
        return; // base case: there's no node to visit
    }

    inOrder($node->left);
    echo $node->value, ' ';
    inOrder($node->right);
}

$root = null;

foreach ([50, 30, 70, 20, 40, 60, 80] as $value) {
    $root = insert($root, $value);
}

inOrder($root); // 20 30 40 50 60 70 80
echo PHP_EOL;

In Python:

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


def insert(node, value):
    if node is None:
        return Node(value)  # found the empty spot: the node is born here

    if value < node.value:
        node.left = insert(node.left, value)
    else:
        node.right = insert(node.right, value)

    return node


def in_order(node):
    if node is None:
        return  # base case: there's no node to visit

    in_order(node.left)
    print(node.value, end=" ")
    in_order(node.right)


root = None

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

in_order(root)  # 20 30 40 50 60 70 80
print()

And in C:

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int value;
    struct Node *left;
    struct Node *right;
};

struct Node *insert(struct Node *node, int value) {
    if (node == NULL) {
        struct Node *new_node = malloc(sizeof(struct Node));

        if (new_node == NULL) {
            return NULL; // out of memory
        }

        new_node->value = value;
        new_node->left = NULL;
        new_node->right = NULL;
        return new_node; // found the empty spot: the node is born here
    }

    if (value < node->value) {
        node->left = insert(node->left, value);
    } else {
        node->right = insert(node->right, value);
    }

    return node;
}

void in_order(struct Node *node) {
    if (node == NULL) {
        return; // base case: there's no node to visit
    }

    in_order(node->left);
    printf("%d ", node->value);
    in_order(node->right);
}

void free_tree(struct Node *node) {
    if (node == NULL) {
        return;
    }

    free_tree(node->left);
    free_tree(node->right);
    free(node); // in C, you give back the memory of each node
}

int main(void) {
    int values[] = {50, 30, 70, 20, 40, 60, 80};
    struct Node *root = NULL;

    for (int i = 0; i < 7; i++) {
        root = insert(root, values[i]);
    }

    in_order(root); // 20 30 40 50 60 70 80
    printf("\n");

    free_tree(root);
    return 0;
}

And in Java:

public class BinarySearchTree {
    static class Node {
        int value;
        Node left;
        Node right;

        Node(int value) {
            this.value = value;
        }
    }

    static Node insert(Node node, int value) {
        if (node == null) {
            return new Node(value); // found the empty spot: the node is born here
        }
        if (value < node.value) {
            node.left = insert(node.left, value);
        } else {
            node.right = insert(node.right, value);
        }
        return node;
    }

    static void inOrder(Node node) {
        if (node == null) {
            return; // base case: there's no node to visit
        }
        inOrder(node.left);
        System.out.print(node.value + " ");
        inOrder(node.right);
    }

    public static void main(String[] args) {
        int[] values = {50, 30, 70, 20, 40, 60, 80};
        Node root = null;
        for (int value : values) {
            root = insert(root, value);
        }
        inOrder(root); // 20 30 40 50 60 70 80
        System.out.println();
    }
}

Did you notice the result? The values came out in ascending order, and I didn’t use any sorting algorithm!!! The rule of smaller on the left and larger on the right already puts everything in place.

And both functions are recursive. Remember that every subtree is also a tree? That’s why recursion fits so well here: the function handles one node and calls itself for the children. The base case is reaching an empty spot.

One detail: in this example, a repeated value goes to the right. It’s a choice, and what matters is always using the same rule.

Why is searching a tree fast?

To look for 60 in the tree from the drawing, you start at the root: 60 is larger than 50, so you go right and forget everything on the left. You reach 70: 60 is smaller, so you go left. Found it! That’s 3 comparisons in a tree of 7 values.

Binary search tree with the path of the search for 60 highlighted: 50, then 70, then 60, and the other nodes dashed
The search for 60 visits three nodes. The other four aren’t even looked at.

Does that remind you of something? It’s the same idea as binary search: in a well-balanced tree, each comparison discards about half of what’s left.

Values in the treeMaximum comparisons
73
1,02310
1,048,57520
Maximum comparisons in a tree with all levels full.

IMPORTANT: the tree is only fast if it’s well balanced. If you insert the values already in order (10, 20, 30, 40…), each one always goes to the right of the previous one, and the tree turns into a “line”, just like a linked list. Then the search goes back to node by node.

Two trees with the values from 10 to 70: one balanced over three levels and another shaped like a list, with seven levels
The insertion order changes the shape of the tree, and the shape changes the speed of the search.

To avoid this, there are balanced trees, like the AVL tree and the red-black tree, which reorganize themselves. But that’s a topic for later. One step at a time!

Just so you can see one of them at work: in Java, the TreeMap class is based on a red-black tree, and TreeSet is built on top of it. With TreeSet, the same seven values come out in order without you writing the tree:

import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        TreeSet<Integer> values = new TreeSet<>();
        for (int value : new int[] {50, 30, 70, 20, 40, 60, 80}) {
            values.add(value);
        }
        System.out.println(values);              // [20, 30, 40, 50, 60, 70, 80]
        System.out.println(values.contains(60)); // true
    }
}

Where do trees show up in everyday life?

The folders on your computer form a tree: a folder has other folders inside, which have other folders… The tags of an HTML page do too. These trees aren’t binary, because a node can have many children, but the idea of root, children and leaves is exactly the same. Whoever understands the binary tree understands the others much more easily.

Now it’s your turn!

Grab pen and paper and insert the values 45, 25, 65, 10 and 30, in that order, into an empty binary search tree. Draw the result. Then answer: which nodes are leaves? And in what sequence does the in-order traversal show the values?

Drawing on paper before running the code is one of the best exercises there is. Don’t skip this step, and don’t ask anyone for the finished drawing! The answer comes in the next article.

In it, we’ll meet the hash table, the structure that can find a value almost without searching. See you there!

Stay confident!!!

Sources:

  • Nick Parlante, Stanford CS Education Library. Binary Trees, with the binary tree as a recursive structure, insert and lookup in a binary search tree, and the time on the order of lg(N) when the tree is balanced.
  • Robert Sedgewick and Kevin Wayne, Princeton University. Algorithms, 3.2: Binary Search Trees, with operations that take time proportional to the height of the tree, a shape that depends on the insertion order, and the inorder traversal that visits the keys in order.
  • Princeton University, COS 226. Binary Search Trees, with the best, typical and worst case, and a height between log2 n and n − 1 (PDF).
  • Virginia Tech, OpenDSA. Binary Trees, with the root, the children of each node, leaves as nodes with two empty children, and subtrees.
  • Pat Morin, Open Data Structures. Chapter 6: Binary Trees, with trees drawn from the root downward, the subtree of a node and leaves as nodes with no children.
  • Stanford University, CS 106B. Binary Search Trees, with the invariant of smaller values on the left and larger ones on the right, and sets and maps built on balanced binary search trees.
  • Cornell University, CS 2110. Binary Search Trees, with the order invariant that lets the search skip part of the tree.
  • University of Washington, CSE 143. Binary Trees, with the recursive definition of a tree (empty, or a root with a left and a right subtree) and the terms root, leaf and subtree.
  • University of Maryland, CMSC 420 (Dave Mount). Lecture 4: Binary Search Trees, with the search that starts at the root and compares the key with each node on the way (PDF).
  • Oracle, Java 21 documentation. TreeMap class, a red-black tree based implementation that keeps the keys in order.
  • Oracle, Java 21 documentation. TreeSet class, with the ordered set based on a TreeMap.
  • The examples were run on PHP 8.3, Python 3.13, GCC 13 and Java 21.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).