AlgoViz

Binary tree

easy 18 min

A binary tree is a hierarchy of nodes where each node has at most two children, left and right, hanging from a single root.

Video lesson · Chapter 1 of 6

The operator at the junction

0:00 / 5:23

Binary trees — The hanging calculator

1:00Reel

Read caption

A crane’s kinetic mobile doubles as an expression tree. The siblings two and three feed a plus node before its parent multiplies by four. Follow the wires down for ingredients. Bring the answers back up.

How it works

Step through the idea, or press Play.

Step 1 of 3

Start at the root. One node with no parent; holding it means holding the whole tree

Understand it

Start here

What a binary tree is

A binary tree is a collection of nodes where each node holds a value and at most two links, called left and right. One node, the root, sits at the top with nothing above it, and the tree grows downward from there like an upside-down tree. Unlike an array or a linked list, data is not in a line: it branches.

The tree used throughout this page

Seven nodes, six edges. 1 is the root; 4, 5, 6 and 7 (green) are leaves because they have no children.
  • Value

    The data the node stores: a number, a word, an operator in an expression.

  • Left link

    A reference to the left child, or None when there is none.

  • Right link

    A reference to the right child, or None. Two links per node is the whole definition.

Vocabulary

Root, parent, child, leaf, sibling

TermMeaningIn the tree above
RootThe topmost node, the only one with no parent1
ParentA node with at least one child1, 2, 3
ChildA node directly below a parent; each has exactly one parent2 and 3 are children of 1
SiblingNodes that share a parent4 and 5; 6 and 7
LeafA node with no children4, 5, 6, 7
Internal nodeAny node that is not a leaf1, 2, 3
SubtreeA node together with everything below it{2, 4, 5}
EdgeThe link between a parent and a child6 edges for 7 nodes
Every node except the root has exactly one edge up to its parent, so a tree with nn nodes always has n−1n - 1 edges.

Measurements

Depth, height and levels

Depth is measured from the top: the number of edges from the root down to a node. The root has depth 0. Height is measured from the bottom: the number of edges on the longest path from a node down to a leaf. Leaves have height 0, and the height of the tree is the height of its root, which is also the greatest depth of any node.

Height as a recurrence

h(∅)=−1,h(v)=1+max⁡(h(v.left),  h(v.right))h(\varnothing) = -1, \qquad h(v) = 1 + \max\big(h(v.\text{left}),\; h(v.\text{right})\big)
With the empty tree at −1-1, a leaf gets 1+max⁡(−1,−1)=01 + \max(-1, -1) = 0. The tree on this page has height 2.
NodeDepth (edges from root)Height (edges to deepest leaf)Level (1-based)
1021
2, 3112
4, 5, 6, 7203

In code

The node class and a recursive definition

Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val = val        self.left = left        self.right = rightdef height(node):                    # edges: leaf 0, empty -1    if node is None:        return -1    return 1 + max(height(node.left), height(node.right))def size(node):    if node is None:        return 0    return 1 + size(node.left) + size(node.right)def leaves(node):    if node is None:        return 0    if node.left is None and node.right is None:        return 1    return leaves(node.left) + leaves(node.right)#        1#      /   \#     2     3#    / \   / \#   4   5 6   7root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))print("height", height(root), "size", size(root), "leaves", leaves(root))   # 2 7 4
A node is a value plus two links. Height, size and leaf count all follow one recursive pattern.
Edit and run it in your browser

The shape of every recursive tree function

Height combines with 1+max⁡(l,r)1 + \max(l, r), size with 1+l+r1 + l + r, leaf count with l+rl + r. Only the base value and the combine step change.

Shapes

Five types of binary tree

  • Perfect

    Every internal node has two children and all leaves are on the same level. Height hh means exactly 2h+1−12^{h+1} - 1 nodes.

  • Full

    Every node has 0 or 2 children, never 1. Then leaves = internal nodes + 1.

  • Complete

    Every level is full except maybe the last, which fills from the left with no gaps. Fits an array with no holes: this is the heap shape.

  • Balanced

    At every node the two subtree heights differ by at most 1. Keeps the height at O(log⁡n)O(\log n).

  • Degenerate

    Every node has one child, so the tree is a chain of height n−1n - 1. It behaves like a linked list.

Classifying a tree

"Full" is a separate yes/no question (does any node have exactly one child?) and can be true or false on any branch of this chart except perfect, which is always full.
TypeHeight for n nodesArray without holes?Example
Perfectlog⁡2(n+1)−1\log_2(n+1) - 1 exactlyYes1 to 7 above
Complete⌊log⁡2n⌋\lfloor \log_2 n \rfloorYesBinary heap
BalancedO(log⁡n)O(\log n)Not alwaysAVL and red-black trees
Full⌊log⁡2n⌋\lfloor \log_2 n \rfloor to (n−1)/2(n-1)/2Not alwaysExpression trees, Huffman trees
Degeneraten−1n - 1No: up to 2n−12^n - 1 cellsSorted values inserted into a plain BST

Counting

Node counts and height bounds

Each level can hold at most twice as many nodes as the level above it. Everything else on this section follows from that one fact.

At most 2^k nodes on level k, at most 2^(h+1) − 1 in total

level k≤2k⟹n  ≤  ∑k=0h2k  =  2h+1−1\text{level } k \le 2^{k} \qquad\Longrightarrow\qquad n \;\le\; \sum_{k=0}^{h} 2^{k} \;=\; 2^{h+1} - 1
A geometric series: 1+2+4+⋯+2h=2h+1−11 + 2 + 4 + \dots + 2^h = 2^{h+1} - 1. For h=2h = 2: at most 7 nodes, reached only by the perfect tree.

Turned around: the smallest possible height

n≤2h+1−1  ⟹  h  ≥  ⌈log⁡2(n+1)⌉−1  =  ⌊log⁡2n⌋,h+1  ≤  nn \le 2^{h+1} - 1 \;\Longrightarrow\; h \;\ge\; \lceil \log_2 (n+1) \rceil - 1 \;=\; \lfloor \log_2 n \rfloor, \qquad h + 1 \;\le\; n
So ⌊log⁡2n⌋≤h≤n−1\lfloor \log_2 n \rfloor \le h \le n - 1. A million nodes can be as shallow as height 19 or as deep as 999,999. Balanced trees stay near the left end; a degenerate chain sits at the right.
n nodesSmallest heightLargest heightMax nodes for that smallest height
1001
7267
83715
1531415
1,00099991,023
1,000,00019999,9991,048,575
Other facts worth knowing: n−1n - 1 edges always; in a full tree, leaves == internal +1+ 1; a perfect tree of height hh has 2h2^h leaves, just over half its nodes.

Storage

Array representation

A complete tree does not need pointers at all. Write its nodes into an array in level order, root at index 0, and the positions alone encode every parent and child.

Index arithmetic (0-based)

left(i)=2i+1,right(i)=2i+2,parent(i)=⌊i−12⌋\text{left}(i) = 2i + 1, \qquad \text{right}(i) = 2i + 2, \qquad \text{parent}(i) = \left\lfloor \frac{i - 1}{2} \right\rfloor
With 1-based indexing they become 2i2i, 2i+12i + 1 and ⌊i/2⌋\lfloor i/2 \rfloor. Index ii is a leaf when 2i+1≥n2i + 1 \ge n, so in a complete tree the leaves are the last ⌈n/2⌉\lceil n/2 \rceil cells.
Index i0123456
Value1234567
Children1, 23, 45, 6leafleafleafleaf
Parentnone001122
The tree on this page as the array [1, 2, 3, 4, 5, 6, 7]. Node 3 at index 2 has its children at 2⋅2+1=52 \cdot 2 + 1 = 5 and 2⋅2+2=62 \cdot 2 + 2 = 6.

Traversals

The four traversals at a glance

A traversal visits every node exactly once. The three depth-first orders differ only in when the node is recorded relative to its two subtrees; level order goes across instead of down. Each one has a full lesson: Tree DFS for preorder, inorder and postorder, and Tree BFS for level order.

TraversalOrderOutput for 1 to 7UsesHelper
PreorderNode, Left, Right1 2 4 5 3 6 7Copy or serialise a tree; prefix expressionsStack / recursion
InorderLeft, Node, Right4 2 5 1 6 3 7Sorted output from a BST; infix expressionsStack / recursion
PostorderLeft, Right, Node4 5 2 6 7 3 1Delete a tree; folder sizes; postfix expressionsStack / recursion
Level orderLevel by level, left to right1 2 3 4 5 6 7Minimum depth, right side view, printing by levelQueue
All four are O(n)O(n) time. Depth-first uses O(h)O(h) stack; level order uses O(w)O(w) queue, where ww is the widest level.

Which traversal do I need?

A rule of thumb, not a law: many problems can be solved with more than one order, but this picks the most natural one.
Python
from collections import dequeclass TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef preorder(node, out):    if node:        out.append(node.val)          # node first        preorder(node.left, out)        preorder(node.right, out)def inorder(node, out):    if node:        inorder(node.left, out)        out.append(node.val)          # node in the middle        inorder(node.right, out)def postorder(node, out):    if node:        postorder(node.left, out)        postorder(node.right, out)        out.append(node.val)          # node lastdef level_order(root):    out, queue = [], deque([root] if root else [])    while queue:        node = queue.popleft()        # first in, first out        out.append(node.val)        queue.extend(c for c in (node.left, node.right) if c)    return outroot = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))for name, walk in (("pre", preorder), ("in", inorder), ("post", postorder)):    out = []    walk(root, out)    print(name.ljust(5), out)print("level", level_order(root))
All four traversals on the same tree. Move one line and preorder becomes inorder or postorder.
Edit and run it in your browser

Complexity

What each operation costs

OperationTimeExtra spaceWhy
Any traversalO(n)O(n)O(h)O(h), level order O(w)O(w)Each node entered once
Height, size, leaf countO(n)O(n)O(h)O(h)A postorder pass
Search for a value (not a BST)O(n)O(n)O(h)O(h)No ordering, so any node could hold it
Insert, given the parent with a free slotO(1)O(1)O(1)O(1)Set one link
Insert at the first free slot (keeps it complete)O(n)O(n)O(w)O(w)Level-order scan to find the slot
Count nodes of a complete treeO(log⁡2n)O(\log^2 n)O(log⁡n)O(\log n)Skip perfect subtrees by formula
Insert is O(1)O(1) only once you already hold a parent with a free slot. Finding that slot is a search, so plain binary trees are rarely used for lookups: that is what a binary search tree adds.

Recursion space is the height

O(log⁡n)⏟balanced  ≤  O(h)  ≤  O(n)⏟degenerate\underbrace{O(\log n)}_{\text{balanced}} \;\le\; O(h) \;\le\; \underbrace{O(n)}_{\text{degenerate}}
Only one root-to-leaf path of calls is alive at once. Python stops at about 1,000 frames, so a skewed tree of 10,000 nodes needs an explicit stack.

Use a binary tree when

  • The data is naturally a hierarchy: expressions, decisions, folders
  • Each step makes a two-way choice
  • You are building a BST, heap or Huffman code on top of it
  • You need parent-child relationships, not positions

Avoid it when

  • The data is flat and linear: use an array or linked list
  • You need fast access by index
  • Memory is tight: two pointers per node add up
  • A plain FIFO or LIFO will do: use a queue or stack

Patterns

Four patterns behind most tree problems

  • DFS recursion

    Process the node and recurse on both sides. Ask: what do I need from my children, and what do I return? Max depth, path sum, same tree.

  • BFS level order

    A queue, with len(queue) read at the start of each round to mark level boundaries. Level order, minimum depth, right side view.

  • Tree construction

    Rebuild from traversals: the first preorder value is the root, and its position in inorder splits the left subtree from the right.

  • Path tracking

    Carry the path from the root, add the node on the way down and remove it on the way back (backtracking). Root-to-leaf paths, path sums, lowest common ancestor.

Answering a tree question in an interview
  1. 1ClarifyBinary tree or BST? Duplicates? Empty tree?
  2. 2Pick the orderLevels: BFS. Children first: postorder.
  3. 3Base caseWhat does None return?
  4. 4CombineTurn the two child answers into this node's answer
  5. 5CostO(n) time, O(h) space; mention skewed trees

Recap

Key takeaways

Key points

  • A binary tree is nodes with at most two children, left and right, under a single root; nn nodes always have n−1n - 1 edges.
  • Depth counts edges down from the root; height counts edges up from the deepest leaf. LeetCode's maximum depth counts nodes, one more.
  • Level kk holds at most 2k2^k nodes, so n≤2h+1−1n \le 2^{h+1} - 1 and ⌊log⁡2n⌋≤h≤n−1\lfloor \log_2 n \rfloor \le h \le n - 1.
  • Perfect ⊂ complete ⊂ balanced. Full means no node has one child. Degenerate is a chain of height n−1n - 1.
  • A complete tree fits an array: children of ii at 2i+12i + 1 and 2i+22i + 2, parent at ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor.
  • Preorder NLR copies, inorder LNR sorts a BST, postorder LRN deletes and aggregates, level order uses a queue.
  • Every traversal is O(n)O(n) time; recursion costs O(h)O(h) space, which is O(n)O(n) on a skewed tree.

Sources