Skip to content

7.1   Binary trees

A binary tree is a nonlinear data structure representing relationships between ancestors and descendants. It embodies the divide-and-conquer idea of splitting in two. Like a linked list, it is built from nodes, each containing a value and references to its left and right children.

class TreeNode:
    """Binary tree node class"""
    def __init__(self, val: int):
        self.val: int = val                # Node value
        self.left: TreeNode | None = None  # Left child reference
        self.right: TreeNode | None = None # Right child reference
/* Binary tree node struct */
struct TreeNode {
    int val;          // Node value
    TreeNode *left;   // Left child pointer
    TreeNode *right;  // Right child pointer
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
/* Binary tree node class */
class TreeNode {
    int val;         // Node value
    TreeNode left;   // Left child reference
    TreeNode right;  // Right child reference
    TreeNode(int x) { val = x; }
}
/* Binary tree node class */
class TreeNode(int? x) {
    public int? val = x;    // Node value
    public TreeNode? left;  // Left child reference
    public TreeNode? right; // Right child reference
}
/* Binary tree node struct */
type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}
/* Constructor */
func NewTreeNode(v int) *TreeNode {
    return &TreeNode{
        Left:  nil, // Left child pointer
        Right: nil, // Right child pointer
        Val:   v,   // Node value
    }
}
/* Binary tree node class */
class TreeNode {
    var val: Int // Node value
    var left: TreeNode? // Left child reference
    var right: TreeNode? // Right child reference

    init(x: Int) {
        val = x
    }
}
/* Binary tree node class */
class TreeNode {
    val; // Node value
    left; // Left child pointer
    right; // Right child pointer
    constructor(val, left, right) {
        this.val = val === undefined ? 0 : val;
        this.left = left === undefined ? null : left;
        this.right = right === undefined ? null : right;
    }
}
/* Binary tree node class */
class TreeNode {
    val: number;
    left: TreeNode | null;
    right: TreeNode | null;

    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = val === undefined ? 0 : val; // Node value
        this.left = left === undefined ? null : left; // Left child reference
        this.right = right === undefined ? null : right; // Right child reference
    }
}
/* Binary tree node class */
class TreeNode {
  int val;         // Node value
  TreeNode? left;  // Left child reference
  TreeNode? right; // Right child reference
  TreeNode(this.val, [this.left, this.right]);
}
use std::rc::Rc;
use std::cell::RefCell;

/* Binary tree node struct */
struct TreeNode {
    val: i32,                               // Node value
    left: Option<Rc<RefCell<TreeNode>>>,    // Left child reference
    right: Option<Rc<RefCell<TreeNode>>>,   // Right child reference
}

impl TreeNode {
    /* Constructor */
    fn new(val: i32) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Self {
            val,
            left: None,
            right: None
        }))
    }
}
/* Binary tree node struct */
typedef struct TreeNode {
    int val;                // Node value
    int height;             // Node height
    struct TreeNode *left;  // Left child pointer
    struct TreeNode *right; // Right child pointer
} TreeNode;

/* Constructor */
TreeNode *newTreeNode(int val) {
    TreeNode *node;

    node = (TreeNode *)malloc(sizeof(TreeNode));
    node->val = val;
    node->height = 0;
    node->left = NULL;
    node->right = NULL;
    return node;
}
/* Binary tree node class */
class TreeNode(val _val: Int) {  // Node value
    var left: TreeNode? = null   // Left child reference
    var right: TreeNode? = null  // Right child reference
}
### Binary tree node class ###
class TreeNode
  attr_accessor :val    # Node value
  attr_accessor :left   # Left child reference
  attr_accessor :right  # Right child reference

  def initialize(val)
    @val = val
  end
end

Each node has two references or pointers, one to its left child and one to its right child. The node is their parent. Its left child and all nodes below that child form its left subtree; the right subtree is defined similarly.

Every non-leaf node has children and at least one nonempty subtree. In Figure 7-1, if node 2 is the parent, its left and right children are nodes 4 and 5. Its left subtree consists of node 4 and everything below it, and its right subtree consists of node 5 and everything below it.

Figure 7-1   Parents, children, and subtrees

Description of Figure 7-1: Nodes and subtrees of a binary tree

The root and its branches illustrate the difference between a direct child node and a whole subtree containing that node and all its descendants.

This perfect binary tree has 4 levels and 15 nodes, rooted at 1. Values run from 1 to 15 level by level, left to right. Nodes 8 through 15 are leaves with no children. The table lists left and right children for the 7 non-leaf nodes, 1 through 7.

An orange area encloses the left subtree of root 1 and a blue area its right subtree. Each area includes the corresponding subtree root and all its descendants.

Left and right children of every non-leaf node in the figure
Parent nodeLeft childRight child
123
245
367
489
51011
61213
71415

For root 1 the left child is the single node 2 and the right child the single node 3. The left subtree rooted at 2 contains 7 nodes: 2, 4, 5, 8, 9, 10, and 11. The right subtree rooted at 3 also contains 7: 3, 6, 7, 12, 13, 14, and 15. A subtree includes its root and all descendants, extending beyond the direct child in this example.

Parent, child, and subtree are relative to the node being considered. Node 1 is the parent of 2 and 3, and 2 is the parent of 4 and 5. The figure labels root 1 “Parent node” because it is the parent of 2 and 3. The root itself has no parent.

7.1.1   Common terminology

Figure 7-2 illustrates common binary-tree terminology.

  • Root: the topmost node, which has no parent.
  • Leaf: a node with no children; both of its child references point to None.
  • Edge: a connection between two nodes, represented by a reference or pointer.
  • A node's level: levels increase from top to bottom, with the root at level 1.
  • A node's degree: its number of children, which is 0, 1, or 2 in a binary tree.
  • A tree's height: the number of edges from the root to its farthest leaf.
  • A node's depth: the number of edges from the root to that node.
  • A node's height: the number of edges from that node to its farthest leaf.

Figure 7-2   Common binary-tree terminology

Description of Figure 7-2: Binary tree roots, leaves, depth, and height

Root and leaf labels identify node positions. Scales on either side show depth and height.

This four-level binary tree has node values inside green circles. Gray arrows lead from parents to their left and right children. Root 1 has children 2 and 3, node 2 has 4 and 5, node 3 has 6 and 7, and node 4 has 8 and 9, each listed left to right. Node 6 has only left child 12; node 7 has left child 14 and right child 15.

Each directed line represents one edge. “Root node” points to the topmost node 1, which has no parent. Six lines from “Leaf node” point to 8, 9, 5, 12, 14, and 15. All six lack children. Leaf 5 is on level 3 and the other five are on level 4, showing that leaves need not share a level.

Horizontal dashed lines align the scales with the tree levels. Both depth and height count edges. At upper left the path from root 1 to node 2 has 1 edge, so node 2 has depth 1. At lower left the paths from node 2 to its farthest leaves 8 and 9 have 2 edges, so node 2 has height 2. The long scale on the right counts 3 edges from root 1 to a deepest leaf: the binary tree has height 3.

From node 2 there is 1 edge to leaf 5 but 2 edges to leaves 8 and 9. Height takes the farthest distance, 2. This four-level tree has height 3 because a path has 1 fewer edge than levels.

Tip

Height and depth are usually measured in edges, but some problems or textbooks count nodes instead. Under that convention, add 1 to both height and depth.

7.1.2   Basic operations

1.   Initializing a binary tree

As with a linked list, first create the nodes, then connect them with references or pointers.

binary_tree.py
# Initialize a binary tree
# Initialize nodes
n1 = TreeNode(val=1)
n2 = TreeNode(val=2)
n3 = TreeNode(val=3)
n4 = TreeNode(val=4)
n5 = TreeNode(val=5)
# Connect nodes with references (pointers)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
binary_tree.cpp
/* Initialize a binary tree */
// Initialize nodes
TreeNode* n1 = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(4);
TreeNode* n5 = new TreeNode(5);
// Connect nodes with references (pointers)
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
binary_tree.java
// Initialize nodes
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// Connect nodes with references (pointers)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.cs
/* Initialize a binary tree */
// Initialize nodes
TreeNode n1 = new(1);
TreeNode n2 = new(2);
TreeNode n3 = new(3);
TreeNode n4 = new(4);
TreeNode n5 = new(5);
// Connect nodes with references (pointers)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.go
/* Initialize a binary tree */
// Initialize nodes
n1 := NewTreeNode(1)
n2 := NewTreeNode(2)
n3 := NewTreeNode(3)
n4 := NewTreeNode(4)
n5 := NewTreeNode(5)
// Connect nodes with references (pointers)
n1.Left = n2
n1.Right = n3
n2.Left = n4
n2.Right = n5
binary_tree.swift
// Initialize nodes
let n1 = TreeNode(x: 1)
let n2 = TreeNode(x: 2)
let n3 = TreeNode(x: 3)
let n4 = TreeNode(x: 4)
let n5 = TreeNode(x: 5)
// Connect nodes with references (pointers)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
binary_tree.js
/* Initialize a binary tree */
// Initialize nodes
let n1 = new TreeNode(1),
    n2 = new TreeNode(2),
    n3 = new TreeNode(3),
    n4 = new TreeNode(4),
    n5 = new TreeNode(5);
// Connect nodes with references (pointers)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.ts
/* Initialize a binary tree */
// Initialize nodes
let n1 = new TreeNode(1),
    n2 = new TreeNode(2),
    n3 = new TreeNode(3),
    n4 = new TreeNode(4),
    n5 = new TreeNode(5);
// Connect nodes with references (pointers)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.dart
/* Initialize a binary tree */
// Initialize nodes
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// Connect nodes with references (pointers)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
binary_tree.rs
// Initialize nodes
let n1 = TreeNode::new(1);
let n2 = TreeNode::new(2);
let n3 = TreeNode::new(3);
let n4 = TreeNode::new(4);
let n5 = TreeNode::new(5);
// Connect nodes with references (pointers)
n1.borrow_mut().left = Some(n2.clone());
n1.borrow_mut().right = Some(n3);
n2.borrow_mut().left = Some(n4);
n2.borrow_mut().right = Some(n5);
binary_tree.c
/* Initialize a binary tree */
// Initialize nodes
TreeNode *n1 = newTreeNode(1);
TreeNode *n2 = newTreeNode(2);
TreeNode *n3 = newTreeNode(3);
TreeNode *n4 = newTreeNode(4);
TreeNode *n5 = newTreeNode(5);
// Connect nodes with references (pointers)
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
binary_tree.kt
// Initialize nodes
val n1 = TreeNode(1)
val n2 = TreeNode(2)
val n3 = TreeNode(3)
val n4 = TreeNode(4)
val n5 = TreeNode(5)
// Connect nodes with references (pointers)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
binary_tree.rb
# Initialize a binary tree
# Initialize nodes
n1 = TreeNode.new(1)
n2 = TreeNode.new(2)
n3 = TreeNode.new(3)
n4 = TreeNode.new(4)
n5 = TreeNode.new(5)
# Connect nodes with references (pointers)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
Visualize execution

2.   Inserting and deleting nodes

As with linked lists, insertion and deletion can be implemented by changing pointers. An example is shown below.

Figure 7-3   Inserting and deleting a binary-tree node

Description of Figure 7-3: Inserting and detaching a binary tree node

Change left-child links to insert or detach an intermediate node P while retaining the entire subtree rooted at 2.

Root 1 (n1) initially has left child 2 (n2) and right leaf 3. Node 2 has left leaf 4 and right leaf 5. The node P to insert holds 0 and both child links are empty. Three panels show preparation, completed insertion, and completed removal, from left to right.

First save the reference to node 2 in n2. In the left panel P is separate from the tree. The middle panel executes n1.left = P and P.left = n2, making the left branch 1→P (0)→2. Node 2 keeps children 4 and 5, while P has no right child. The right panel executes n1.left = n2 to bypass P and restore the original tree. Root 1 keeps right child 3 throughout.

Detaching P restores the original links and makes P unreachable from the root. That does not establish that the object’s memory was freed. The entire original left subtree is still present.

binary_tree.py
# Insert and delete a node
p = TreeNode(0)
# Insert node P between n1 and n2
n1.left = p
p.left = n2
# Delete node P
n1.left = n2
binary_tree.cpp
/* Insert and delete a node */
TreeNode* P = new TreeNode(0);
// Insert node P between n1 and n2
n1->left = P;
P->left = n2;
// Delete node P
n1->left = n2;
// Free the memory
delete P;
binary_tree.java
TreeNode P = new TreeNode(0);
// Insert node P between n1 and n2
n1.left = P;
P.left = n2;
// Delete node P
n1.left = n2;
binary_tree.cs
/* Insert and delete a node */
TreeNode P = new(0);
// Insert node P between n1 and n2
n1.left = P;
P.left = n2;
// Delete node P
n1.left = n2;
binary_tree.go
/* Insert and delete a node */
// Insert node P between n1 and n2
p := NewTreeNode(0)
n1.Left = p
p.Left = n2
// Delete node P
n1.Left = n2
binary_tree.swift
let P = TreeNode(x: 0)
// Insert node P between n1 and n2
n1.left = P
P.left = n2
// Delete node P
n1.left = n2
binary_tree.js
/* Insert and delete a node */
let P = new TreeNode(0);
// Insert node P between n1 and n2
n1.left = P;
P.left = n2;
// Delete node P
n1.left = n2;
binary_tree.ts
/* Insert and delete a node */
const P = new TreeNode(0);
// Insert node P between n1 and n2
n1.left = P;
P.left = n2;
// Delete node P
n1.left = n2;
binary_tree.dart
/* Insert and delete a node */
TreeNode P = new TreeNode(0);
// Insert node P between n1 and n2
n1.left = P;
P.left = n2;
// Delete node P
n1.left = n2;
binary_tree.rs
let p = TreeNode::new(0);
// Insert node P between n1 and n2
n1.borrow_mut().left = Some(p.clone());
p.borrow_mut().left = Some(n2.clone());
// Delete node p
n1.borrow_mut().left = Some(n2);
binary_tree.c
/* Insert and delete a node */
TreeNode *P = newTreeNode(0);
// Insert node P between n1 and n2
n1->left = P;
P->left = n2;
// Delete node P
n1->left = n2;
// Free the memory
free(P);
binary_tree.kt
val P = TreeNode(0)
// Insert node P between n1 and n2
n1.left = P
P.left = n2
// Delete node P
n1.left = n2
binary_tree.rb
# Insert and delete a node
_p = TreeNode.new(0)
# Insert node _p between n1 and n2
n1.left = _p
_p.left = n2
# Delete the node
n1.left = n2
Visualize execution

Tip

Inserting a node may change the tree's logical structure, while deleting a node generally means deleting it and all its subtrees. Meaningful insertion and deletion operations therefore usually require several coordinated steps.

7.1.3   Common types of binary trees

1.   Perfect binary trees

In a perfect binary tree, every level is completely filled, as shown below. Leaves have degree \(0\), and all other nodes have degree \(2\). A tree of height \(h\) has \(2^{h+1} - 1\) nodes, an exponential relationship reminiscent of cell division in nature.

Tip

In Chinese-language resources, a perfect binary tree is often called 满二叉树.

Figure 7-4   A perfect binary tree

Description of Figure 7-4: Perfect binary tree: every level is completely filled

In a perfect binary tree every level is full and all leaves are on the bottom level.

The nodes in the four-level tree on the left have no value labels. Their number doubles each level: 1 root on the first level, 2 nodes on the second, 4 on the third, and 8 leaves on the fourth. The gray note below reads “Every level is completely filled.”

Every internal node has both a left and a right child. All 8 leaves line up on the bottom, fourth level. The title on the right reads “Perfect binary tree.”

Counting gives four levels, 15 nodes, and a height of 3 edges. In general a perfect binary tree of height h has 2 to the power (h+1), minus 1, nodes.

2.   Complete binary trees

Only the lowest level of a complete binary tree may be incomplete, and its nodes must fill that level consecutively from left to right, as shown below. Every perfect binary tree is also complete.

Figure 7-5   A complete binary tree

Description of Figure 7-5: Complete binary tree: the last level fills from left to right without gaps

The first three levels are full. The fourth level occupies its five leftmost positions, leaving only the three rightmost positions empty.

The tree on the left has four levels and no node values. The first three levels contain 1, 2, and 4 nodes. From left to right on level three, each of the first two nodes has both children, the third has only a left child, and the fourth has no children. Thus the five leaves on level four occupy its five leftmost positions.

The right-hand title reads “Complete binary tree.” A long arrow points left beneath the tree. The gray note says, “The lowest level is filled from the left; all other levels are full.” There can be no gaps between nodes on the last level.

Counting gives height 3 and 12 nodes, satisfying the definition of a complete binary tree. Three positions on the right of level four are empty, so the tree is not perfect.

3.   Full binary trees

In a full binary tree, every node other than a leaf has exactly two children, as shown below.

Figure 7-6   A full binary tree

Description of Figure 7-6: Full binary tree: every node has degree 0 or 2

A full binary tree constrains each node’s number of children. It does not require every level to be full.

The tree on the left has four levels and 7 unlabeled nodes. The root’s right child is a leaf. Its left child has two children: the left one is a leaf and the right one branches into two more leaves.

A node’s degree is its number of children. The title reads “Full binary tree,” and the gray box says “Every node has 0 or 2 children.” Three internal nodes all have degree 2 and 4 leaves have degree 0. No node has degree 1. The 4 leaves occur on levels two, three, and four.

A full binary tree requires each node to have 0 or 2 children. Levels may be partially filled and leaves may occur at different levels.

4.   Balanced binary trees

In a balanced binary tree, the heights of the left and right subtrees of every node differ by at most 1, as shown below.

Figure 7-7   A balanced binary tree

Description of Figure 7-7: Balanced binary tree: subtree heights differ by at most 1 at every node

The tree is asymmetric but meets the balance condition at every node.

The box on the right defines d as left subtree height minus right subtree height. Every node must satisfy |d| ≤ 1. Here d measures height difference, not node degree. Heights count edges, with 0 for a leaf and −1 for an empty subtree.

The tree on the left has four levels and 8 nodes with no value labels. The root’s left child has a left leaf and no right subtree. Its label is d = 1.

The root’s right child has two children. Its left child is internal and has two leaves, while its right child is itself a leaf. The root’s right child is labeled d = 1 and its left child d = 0. All four leaves have two empty subtrees and are labeled d = 0.

The root’s left subtree has height 1 and its right subtree height 2, so the root is labeled d = −1. Every other node’s height difference is also at most 1 in absolute value, so the tree is balanced.

To determine balance, check every node. Checking only the root’s height difference is insufficient.

7.1.4   Degeneration of a binary tree

Figure 7-8 shows ideal and degenerate tree structures. When every level is full, the tree is perfect. When every node lies along one side, the tree degenerates into a linked list.

  • A perfect binary tree is the ideal case, making full use of divide and conquer.
  • A linked list is the opposite extreme: operations become linear, with time complexity degrading to \(O(n)\).

Figure 7-8   Best and worst binary-tree structures

Description of Figure 7-8: An ideal binary tree and a tree reduced to a chain

The same seven nodes produce different heights depending on whether they branch or connect in a single chain.

The left panel is labeled “Ideal structure” and “Perfect binary tree.” Root 1 has left and right children 2 and 3, node 2 has children 4 and 5, and node 3 has children 6 and 7. All 4 bottom nodes, 4, 5, 6, and 7, are leaves. The tree has 3 levels. From root 1 to any leaf there are 2 edges, so its height is 2.

The right panel is labeled “Degenerate structure” and “Linked list.” All 7 nodes lean left in the chain 1 → 2 → 3 → 4 → 5 → 6 → 7. Every right link is empty. There are 7 levels and 6 edges from root 1 to the only leaf 7, giving height 6.

When all levels are full, a perfect binary tree has minimum height and can exploit divide and conquer. A tree that degenerates into a one-sided linked list reaches maximum height and operations along a path can take linear time.

As Table 7-1 shows, quantities such as leaf count, total node count, and height reach their maximum or minimum values in these best and worst structures.

Table 7-1   Best and worst binary-tree structures

Perfect binary tree Linked list
Nodes at level \(i\) \(2^{i-1}\) \(1\)
Leaves in a tree of height \(h\) \(2^h\) \(1\)
Total nodes in a tree of height \(h\) \(2^{h+1} - 1\) \(h + 1\)
Height of a tree with \(n\) nodes \(\log_2 (n+1) - 1\) \(n - 1\)
Share your insights, questions, or suggestions in the comments