Binary Trees

November 19, 2025
#binary-tree #tree #data-structures #tree-traversal #algorithms #interviewing

Introduction

A binary tree is a hierarchical data structure where each node has at most two children, referred to as the left child and right child. Unlike linear data structures like arrays or linked lists, binary trees organize data in a hierarchical, branching structure that enables efficient searching, sorting, and hierarchical representation.

Binary trees are fundamental to computer science and appear in file systems, databases, compilers, and countless algorithms. By the end of this tutorial, you’ll understand different types of binary trees, how to traverse them, and when to use them.

If you’re new to data structures, review Big-O Notation, Linked Lists, and Queues first.

What is a binary tree?

A binary tree consists of nodes where each node contains:

  1. Data (or value)
  2. Left child pointer
  3. Right child pointer

Key properties:

  • The root is the topmost node
  • Nodes with no children are called leaves (or leaf nodes)
  • The height of a tree is the longest path from root to leaf
  • The depth of a node is its distance from the root
  • Each node can have 0, 1, or 2 children

Types of binary trees

1. Full Binary Tree

Every node has either 0 or 2 children (no node has exactly 1 child).

       1
      / \
     2   3
    / \
   4   5

2. Complete Binary Tree

All levels are completely filled except possibly the last, which is filled from left to right.

       1
      / \
     2   3
    / \  /
   4  5 6

3. Perfect Binary Tree

All internal nodes have 2 children, and all leaves are at the same level.

       1
      / \
     2   3
    / \ / \
   4  5 6  7

4. Balanced Binary Tree

The height difference between left and right subtrees is at most 1 for every node.

       1
      / \
     2   3
    /   / \
   4   5   6

5. Degenerate (Skewed) Tree

Each parent node has only one child (essentially a linked list).

1
 \
  2
   \
    3
     \
      4

Why use binary trees?

Choose binary trees when:

  1. You need hierarchical data representation (file systems, organization charts)
  2. You need efficient searching in sorted data (Binary Search Trees)
  3. You’re implementing priority queues (heaps)
  4. You need to evaluate expressions (expression trees)
  5. You’re building decision trees or game trees
  6. You need efficient insertion and deletion with ordering

Avoid binary trees when:

Real-world applications

Binary trees are used extensively:

  • File systems: Directory structures
  • Databases: B-trees and B+ trees for indexing
  • Compilers: Abstract syntax trees (AST) for parsing
  • Decision making: Decision trees in AI/ML
  • Routing: Binary trees in network routing algorithms
  • Game development: Game trees for AI decisions
  • Huffman coding: Data compression algorithms
  • Expression evaluation: Mathematical expression trees

Binary tree implementation

Node structure and basic tree

Tree traversal methods

Traversal is the process of visiting every node in the tree exactly once in a specific order.

1. In-Order Traversal (Left, Root, Right)

Visit left subtree, then root, then right subtree. For Binary Search Trees, this gives sorted order.

2. Pre-Order Traversal (Root, Left, Right)

Visit root first, then left subtree, then right subtree. Useful for copying trees.

3. Post-Order Traversal (Left, Right, Root)

Visit left subtree, then right subtree, then root. Useful for deleting trees.

4. Level-Order Traversal (Breadth-First)

Visit nodes level by level from left to right. Uses a queue.

Implementation of all traversals

Common binary tree operations

Finding maximum value

Checking if tree is balanced

Mirror/Invert a binary tree

Complexity analysis

Operation Average Case Worst Case Notes
Search O(n) O(n) Must check all nodes in general binary tree
Insert O(n) O(n) Finding position requires traversal
Delete O(n) O(n) Finding and removing node
Traversal O(n) O(n) Must visit every node
Height O(n) O(n) Must check all paths
Space O(n) O(n) Storage for n nodes

Note: For balanced binary search trees, search/insert/delete are O(log n).

Common pitfalls

  • Not handling null nodes: Always check for null before accessing node properties
  • Stack overflow: Deep recursion on unbalanced trees can cause stack overflow
  • Modifying during traversal: Be careful when modifying tree structure during traversal
  • Confusing traversal orders: Know when to use each traversal type
  • Memory leaks: In manual-memory languages, ensure nodes are properly freed
  • Off-by-one in height: Remember that a single node has height 1, not 0

When to prefer other data structures

  • Need O(1) access by index → Use array
  • Need O(1) key lookup → Use hash table
  • Need FIFO/LIFO → Use queue/stack
  • Need guaranteed O(log n) operations → Use balanced BST (AVL, Red-Black)
  • Need range queries → Use segment tree or Fenwick tree

Practice problems

  1. Find the lowest common ancestor (LCA) of two nodes
  2. Determine if two binary trees are identical
  3. Find the diameter of a binary tree (longest path between any two nodes)
  4. Serialize and deserialize a binary tree
  5. Find all root-to-leaf paths that sum to a given value
  6. Convert a binary tree to its mirror image iteratively
  7. Find the maximum path sum in a binary tree
  8. Check if a binary tree is a subtree of another tree
  9. Print all nodes at distance K from a given node
  10. Construct a binary tree from in-order and pre-order traversals
  11. Find the vertical order traversal of a binary tree
  12. Convert a binary tree to a doubly linked list
  13. Find the boundary traversal of a binary tree
  14. Check if a binary tree is symmetric (mirror of itself)
  15. Find the right view of a binary tree

Complexity summary

  • Time complexity:
    • Traversal: O(n) — visit all nodes
    • Search (unbalanced): O(n) — may need to check all nodes
    • Height: O(n) — must check all paths
    • Most operations: O(n) for general binary trees
  • Space complexity:
    • Storage: O(n) for n nodes
    • Recursion stack: O(h) where h is height (O(log n) balanced, O(n) worst case)

Binary trees form the foundation for more advanced tree structures like Binary Search Trees, AVL trees, and heaps. Understanding binary trees deeply will prepare you for these more specialized variants.

Thanks for visiting
We are actively updating content to this site. Thanks for visiting! Please bookmark this page and visit again soon.
Sponsor