Previous Topic
foundational_prerequisite
0.94
Provides the core vocabulary and structural measures necessary to define, classify, and reason about binary trees.

Binary Trees

data structures algorithms software engineering computer science programming complexity analysis
A binary tree is a hierarchical data structure where each node has at most two children, commonly referred to as the left and right child. Binary trees underpin many algorithms and specialized structures, including binary search trees, heaps, and expression trees. Key operations include traversals (preorder, inorder, postorder, level-order), queries (height, size, leaf count), and structural transformations (mirror, rotations in balanced variants). Performance often depends on the tree’s height, with balanced trees enabling logarithmic-time operations.

Overview

A binary tree is a hierarchical data structure composed of nodes. Each node can have up to two children, typically called the left and right child. Binary trees are foundational in computer science, supporting a wide array of algorithms and specialized structures like binary search trees, heaps, and expression trees.

For precise definitions of terms like root, leaf, height, depth, level, and path, see tree_terminology. This page focuses on the structure and general algorithms for binary trees.

Key Properties

  • Node degree: Each node has at most two children.
  • Height (h): Longest path length from the root to a leaf. An empty tree often has height −1 or 0 by convention.
  • Size (n): Number of nodes in the tree.
  • Level capacity: At depth d, there are at most 2^d nodes.
  • Upper bound on size: For height h, n ≤ 2^(h+1) − 1.
  • Special forms: Full (every node has 0 or 2 children), Complete (all levels filled except possibly last, filled left-to-right), Perfect (all leaves at same depth, all internal nodes have 2 children).
  • Balance: A tree is balanced if its height is O(log n), which keeps many operations efficient.

Representations

Pointer/Reference-based

// Example in a C-like style
struct Node {
  Value value;
  Node* left;
  Node* right;
};

This is flexible and works for any shape of binary tree.

Array-based (for complete trees)

Use an array where index i stores a node, with children at 2i+1 and 2i+2 (0-based). This is common for heaps due to memory locality and implicit structure.

Traversals

  • Preorder (Root, Left, Right): Useful for copying/serializing trees.
  • Inorder (Left, Root, Right): Yields sorted order in binary search trees.
  • Postorder (Left, Right, Root): Useful for deleting/freeing trees and evaluating expression trees.
  • Level-order (Breadth-First): Visits nodes by level using a queue.
# Recursive traversal in Python
class Node:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def preorder(root):
    if not root: return
    print(root.val)
    preorder(root.left)
    preorder(root.right)

def inorder(root):
    if not root: return
    inorder(root.left)
    print(root.val)
    inorder(root.right)

def postorder(root):
    if not root: return
    postorder(root.left)
    postorder(root.right)
    print(root.val)

def level_order(root):
    if not root: return
    from collections import deque
    q = deque([root])
    while q:
        node = q.popleft()
        print(node.val)
        if node.left: q.append(node.left)
        if node.right: q.append(node.right)

Core Operations and Algorithms

  • Search (general binary tree): Without an ordering property, worst-case O(n). Use DFS or BFS.
  • Insert: In a general binary tree, insertion position is application-specific (e.g., first available spot for a complete shape). In ordered variants (like BSTs), insertion follows a key-based rule.
  • Delete: Removing a node in a general binary tree may require re-linking a subtree or structural rules specific to the application (e.g., heap deletion uses last element replacement then heapify).
  • Compute height/size/leaves: Typically O(n) via recursion or iterative traversal.
  • Mirror (invert) tree: Swap left and right pointers at every node (O(n)).
  • Lowest Common Ancestor (LCA): In a general tree, O(n) via two-path tracing or single-pass recursion; faster with parent pointers or preprocessing.

Complexity

  • Let h be the height and n the number of nodes.
  • Traversal: O(n) time, O(h) auxiliary space for recursion/stack; BFS uses O(w) queue space where w is max width.
  • Search/Insert/Delete (general): O(n) time; in structured variants (e.g., balanced BSTs) typical operations are O(log n).

Applications

  • Expression trees: Represent and evaluate arithmetic/logical expressions.
  • Priority queues (heaps): Complete binary trees stored as arrays.
  • Compression (Huffman trees): Optimal prefix codes from a binary tree.
  • Range queries: Segment trees and Fenwick trees are binary-based structures for sums/min/max.
  • Decision processes: Binary decision trees for classification and game search.
  • Syntax and parsing: Abstract syntax trees (ASTs) often contain binary operators as binary subtrees.

Recursive vs. Iterative Approaches

Many binary tree algorithms are naturally recursive, reflecting the tree’s self-similarity. Iterative versions use explicit stacks for DFS or queues for BFS to control space and avoid call-stack limits.

Common Pitfalls

  • Confusing binary trees with binary search trees—ordering rules apply only to BSTs.
  • Unbalanced growth leading to height O(n) and degraded performance.
  • Stack overflow with deep recursion; consider iterative traversals.
  • Forgetting null checks when re-linking nodes during insert/delete.

Practice Ideas

  • Implement the four standard traversals (both recursive and iterative).
  • Write functions to compute height, size, leaf count, and to mirror a tree.
  • Serialize and deserialize a binary tree using preorder with null markers or level-order.
  • Compare pointer-based vs. array-based representations on complete vs. sparse trees.

Related Variants and Extensions

  • Binary Search Trees (BSTs): Maintain an in-order key property for fast search.
  • Balanced Trees: AVL and Red-Black trees keep height logarithmic.
  • Heaps: Specialized binary trees for priority queues.
  • Segment/Fenwick Trees: Binary-based structures for efficient range queries.

Context from Referenced By

Context from Related Topics
Pop Quiz
Topic: binary_trees
Level: 1
True or False:

In a 0-based array representation of a complete binary tree, the children of the node at index i are located at indices 2i+1 and 2i+2.

Topic: binary_trees
Level: 1
Multiple Choice:

In a binary search tree (BST), which traversal visits the nodes in sorted (nondecreasing) order of their keys?

Topic: binary_trees
Level: 1
Fill in the Blank:

Level-order traversal of a binary tree is typically implemented using a _____.

Topic: binary_trees
Level: 2
True or False:

In a full binary tree, every node has either zero or two children.

Topic: binary_trees
Level: 2
Multiple Choice:

For a binary tree of height h, what is the maximum possible number of nodes?

Topic: binary_trees
Level: 2
Fill in the Blank:

A binary tree is considered balanced if its height is _____ with respect to the number of nodes n.

Topic: binary_trees
Level: 3
True or False:

In any binary tree, the number of nodes at depth d is at most 2^d.

Topic: binary_trees
Level: 3
Multiple Choice:

Which traversal order is most appropriate for safely deleting/freeing all nodes of a binary tree?

Topic: binary_trees
Level: 3
Fill in the Blank:

Heaps are commonly stored in arrays because they correspond to a _____ binary tree.

Topic: binary_trees
Level: 4
True or False:

Depth-first traversals of a binary tree (preorder, inorder, postorder) each take O(n) time and O(h) auxiliary space, where n is the number of nodes and h is the tree's height.

Topic: binary_trees
Level: 4
Multiple Choice:

During a level-order (breadth-first) traversal of a binary tree, what is the worst-case auxiliary space used by the queue in terms of the tree's maximum width w?

Topic: binary_trees
Level: 4
Fill in the Blank:

The mirror (invert) operation on a binary tree swaps the _____ at every node.

Topic: binary_trees
Level: 5
True or False:

Without an ordering property, searching for a value in a binary tree takes O(n) time in the worst case.

Topic: binary_trees
Level: 5
Multiple Choice:

Which statement correctly defines a perfect binary tree?

Topic: binary_trees
Level: 5
Fill in the Blank:

When serializing a binary tree using preorder for unique reconstruction, you should include _____ for missing children.

Next Topic
defines
0.95

Binary Search Trees
Binary search trees are defined by taking the binary tree structure and adding an ordering invariant to support efficient search, insert, and delete operations.
used_by
0.95

Parsers
Binary search trees specialize the binary tree structure by enforcing an ordering property (left < node < right) to support efficient search, insert, and delete operations.
used_by
0.95

Compilers
Binary search trees are a specialization of binary trees that add an ordering invariant to enable logarithmic-time search, insertion, and deletion when balanced.
used_by
0.94

Heaps
Heaps are specialized binary trees that enforce a complete shape and heap-order property, enabling O(log n) insert/extract and O(1) find-min/max; implementations often use an array as an implicit binary tree.
used_by
0.94

Abstract Syntax Trees
Binary search trees specialize binary trees by enforcing an ordering invariant on node keys, enabling efficient search, insertion, and deletion.
used_by
0.92

Segment Trees
Binary search trees specialize binary trees by enforcing an ordering invariant on keys, enabling efficient search, insert, and delete operations when the tree is balanced.
used_by
0.9

Balanced Trees
Balanced trees (e.g., AVL, Red-Black) specialize binary trees by enforcing balance criteria and using rotations to maintain near-logarithmic height.
used_by
0.9

Avl Trees
AVL trees are self-balancing variants that build on binary tree structure and operations to guarantee logarithmic-time lookups and updates.
contains
0.9

Red Black Trees
Red-black trees are a balanced specialization of binary trees that add coloring rules and rotations to maintain near-logarithmic height.
used_by
0.88

Expression Trees
Expression trees apply the binary tree structure to represent and evaluate arithmetic and logical expressions, with operators as internal nodes and operands as leaves.
used_by
0.88

Huffman Coding
Huffman coding builds a binary Huffman tree to assign optimal prefix codes, relying on tree structure and traversals for encoding and decoding.
used_by
0.87

Depth First Search
Depth-first search is the canonical traversal on binary trees, instantiated as preorder, inorder, and postorder.
related_to
0.86

Breadth First Search
Breadth-first search performs level-order traversal on binary trees, visiting nodes level by level using a queue.
used_by
0.84

Priority Queues
Priority queues are commonly implemented with binary heaps, a specialized binary tree that enables efficient insert and extract-min/max operations.
used_by
0.56

Fenwick Trees
Fenwick trees (binary indexed trees) model an implicit binary tree over array indices via least-significant-bit links; grasping binary tree hierarchy and subtree aggregation helps explain BIT’s O(log n) prefix-sum queries and updates.