In this article
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.

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:

| Value | Path taken | Where it goes |
|---|---|---|
| 50 | The tree is empty | Becomes the root |
| 30 | Smaller than 50 | Left of 50 |
| 70 | Larger than 50 | Right of 50 |
| 20 | Smaller than 50, smaller than 30 | Left of 30 |
| 40 | Smaller than 50, larger than 30 | Right of 30 |
| 60 | Larger than 50, smaller than 70 | Left of 70 |
| 80 | Larger than 50, larger than 70 | Right of 70 |
See the animation of insertion and search in the tree

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.

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 tree | Maximum comparisons |
|---|---|
| 7 | 3 |
| 1,023 | 10 |
| 1,048,575 | 20 |
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.

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.

Continue the conversation