Binary tree
easy 18 minA 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
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.
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
Value
The data the node stores: a number, a word, an operator in an expression.
Left link
A reference to the left child, or
Nonewhen 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
| Term | Meaning | In the tree above |
|---|---|---|
| Root | The topmost node, the only one with no parent | 1 |
| Parent | A node with at least one child | 1, 2, 3 |
| Child | A node directly below a parent; each has exactly one parent | 2 and 3 are children of 1 |
| Sibling | Nodes that share a parent | 4 and 5; 6 and 7 |
| Leaf | A node with no children | 4, 5, 6, 7 |
| Internal node | Any node that is not a leaf | 1, 2, 3 |
| Subtree | A node together with everything below it | {2, 4, 5} |
| Edge | The link between a parent and a child | 6 edges for 7 nodes |
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
| Node | Depth (edges from root) | Height (edges to deepest leaf) | Level (1-based) |
|---|---|---|---|
| 1 | 0 | 2 | 1 |
| 2, 3 | 1 | 1 | 2 |
| 4, 5, 6, 7 | 2 | 0 | 3 |
In code
The node class and a recursive definition
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 4The shape of every recursive tree function
Shapes
Five types of binary tree
Perfect
Every internal node has two children and all leaves are on the same level. Height means exactly 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 .
Degenerate
Every node has one child, so the tree is a chain of height . It behaves like a linked list.
Classifying a tree
| Type | Height for n nodes | Array without holes? | Example |
|---|---|---|---|
| Perfect | exactly | Yes | 1 to 7 above |
| Complete | Yes | Binary heap | |
| Balanced | Not always | AVL and red-black trees | |
| Full | to | Not always | Expression trees, Huffman trees |
| Degenerate | No: up to cells | Sorted 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
Turned around: the smallest possible height
| n nodes | Smallest height | Largest height | Max nodes for that smallest height |
|---|---|---|---|
| 1 | 0 | 0 | 1 |
| 7 | 2 | 6 | 7 |
| 8 | 3 | 7 | 15 |
| 15 | 3 | 14 | 15 |
| 1,000 | 9 | 999 | 1,023 |
| 1,000,000 | 19 | 999,999 | 1,048,575 |
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)
| Index i | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Value | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| Children | 1, 2 | 3, 4 | 5, 6 | leaf | leaf | leaf | leaf |
| Parent | none | 0 | 0 | 1 | 1 | 2 | 2 |
[1, 2, 3, 4, 5, 6, 7]. Node 3 at index 2 has its children at and .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.
| Traversal | Order | Output for 1 to 7 | Uses | Helper |
|---|---|---|---|---|
| Preorder | Node, Left, Right | 1 2 4 5 3 6 7 | Copy or serialise a tree; prefix expressions | Stack / recursion |
| Inorder | Left, Node, Right | 4 2 5 1 6 3 7 | Sorted output from a BST; infix expressions | Stack / recursion |
| Postorder | Left, Right, Node | 4 5 2 6 7 3 1 | Delete a tree; folder sizes; postfix expressions | Stack / recursion |
| Level order | Level by level, left to right | 1 2 3 4 5 6 7 | Minimum depth, right side view, printing by level | Queue |
Which traversal do I need?
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))Complexity
What each operation costs
| Operation | Time | Extra space | Why |
|---|---|---|---|
| Any traversal | , level order | Each node entered once | |
| Height, size, leaf count | A postorder pass | ||
| Search for a value (not a BST) | No ordering, so any node could hold it | ||
| Insert, given the parent with a free slot | Set one link | ||
| Insert at the first free slot (keeps it complete) | Level-order scan to find the slot | ||
| Count nodes of a complete tree | Skip perfect subtrees by formula |
Recursion space is the height
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.
- 1ClarifyBinary tree or BST? Duplicates? Empty tree?
- 2Pick the orderLevels: BFS. Children first: postorder.
- 3Base caseWhat does None return?
- 4CombineTurn the two child answers into this node's answer
- 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; nodes always have 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 holds at most nodes, so and .
- Perfect ⊂ complete ⊂ balanced. Full means no node has one child. Degenerate is a chain of height .
- A complete tree fits an array: children of at and , parent at .
- Preorder NLR copies, inorder LNR sorts a BST, postorder LRN deletes and aggregates, level order uses a queue.
- Every traversal is time; recursion costs space, which is on a skewed tree.