A tree is a set of nodes connected by edges with one designated root, no cycles, and exactly one path between any two nodes. A binary tree limits every node to at most two ordered children, left and right. That small restriction is the foundation for binary search trees, heaps, segment trees, expression trees and Huffman codes, so the vocabulary and shapes on this page show up everywhere else in the module.
Think of it like
A company org chart
The CEO sits at the top (the root). Every other employee reports to exactly one manager (their parent), people with no reports are leaves, and a whole department is a subtree. Your depth is how many levels sit between you and the CEO; the tree's height is the longest chain of command. A binary tree is a company where no manager is allowed more than two direct reports.
What makes something a tree
Formally, a tree is a connected, acyclic graph. Pick one node as the root and every other node gets exactly one parent: the next node on its unique path back to the root. That single-parent rule is why a tree with n nodes always has exactly n - 1 edges: each node except the root contributes the one edge to its parent.
1 depth 0
/ \
2 3 depth 1
/ \ \
4 5 6 depth 2
/
7 depth 3- Root
- The unique node with no parent (
1above). Every traversal starts here. - Parent / child
- Adjacent nodes where the parent is closer to the root.
2is the parent of4and5. - Siblings
- Nodes that share a parent, such as
4and5. - Leaf (external node)
- A node with no children:
4,7and6. Every other node is an internal node. - Degree
- The number of children of a node. In a binary tree it is 0, 1 or 2. Node
3has degree 1. - Ancestor / descendant
- Every node on the path from a node up to the root is an ancestor. The ancestors of
7are5,2and1. - Subtree
- A node together with all of its descendants. The subtree rooted at
2contains{2, 4, 5, 7}. - Depth (level)
- The number of edges from the root down to the node. The root has depth 0;
7has depth 3. - Height
- For a node, the number of edges on the longest downward path to a leaf. A leaf has height 0. The height of the tree is the height of its root (3 here).
Types of binary trees
The same set of values can form wildly different shapes, and the shape decides how fast every operation runs. These names come up constantly in interviews and textbooks, so it pays to keep them straight.
| Type | Definition | Why it matters |
|---|---|---|
| Full (proper, strict) | Every node has 0 or 2 children, never exactly 1 | Leaves = internal nodes + 1. Expression trees and Huffman trees are full. |
| Complete | Every level is full except possibly the last, which is filled from the left | Stores perfectly in an array with no gaps. Every binary heap is complete. |
| Perfect | All internal nodes have 2 children and all leaves share the same depth | The densest possible shape: exactly 2^(h+1) - 1 nodes. |
| Balanced | At every node, the heights of the two subtrees differ by at most 1 | Guarantees height O(log n). AVL trees enforce exactly this rule. |
| Degenerate (pathological) | Every internal node has exactly one child | Height n - 1: effectively a linked list, so operations degrade to O(n). |
Balanced: height ≈ log₂ n
- 1,000,000 nodes fit in about 20 levels
- Search, insert and delete in a BST cost O(log n)
- Recursion depth stays tiny
Degenerate: height = n - 1
- 1,000,000 nodes form a chain 1,000,000 long
- Every BST operation costs O(n)
- Recursive code can overflow the call stack
Properties worth memorizing
Level d of a binary tree can hold at most 2^d nodes, because each level at most doubles the previous one. Summing the levels of a tree of height h gives the maximum node count.
- Edges: a tree with
nnodes has exactlyn - 1edges. - Null links: a binary tree with
nnodes has2nchild slots, of whichn - 1are used, son + 1are null. Threaded trees and Morris traversal exploit these spare pointers. - Full trees: if
Iis the number of internal nodes, the number of leaves isL = I + 1, and the total is2I + 1(always odd). - Shape count: the number of structurally different binary trees with
nnodes is the Catalan numberC(n) = (2n)! / ((n + 1)! n!): 1, 1, 2, 5, 14, 42, …
Min height, n = 10⁶
19
⌊log₂ 1,000,000⌋
Max height, n = 10⁶
999,999
a degenerate chain
Perfect tree, h = 30
≈2.1 B
2³¹ − 1 nodes
Null links, n = 10⁶
1,000,001
always n + 1
Representing a binary tree in memory
Linked nodes
The general-purpose representation is a node object holding a value plus left and right references (and sometimes a parent reference for upward navigation). It handles any shape, uses O(n) memory, and makes structural changes such as rotations a matter of rewiring a few pointers.
An array, for complete trees
A complete tree has no gaps when read level by level, so you can store it in an array in level order and drop the pointers entirely. Parent and child positions become simple arithmetic, which is cache-friendly and compact. This is exactly how Heaps & Priority Queues and Segment Trees are stored.
| Relation | 0-based index | 1-based index |
|---|---|---|
Left child of i | 2i + 1 | 2i |
Right child of i | 2i + 2 | 2i + 1 |
Parent of i | ⌊(i - 1) / 2⌋ | ⌊i / 2⌋ |
| Last internal node (n nodes) | ⌊n / 2⌋ - 1 | ⌊n / 2⌋ |
Is i a leaf? | 2i + 1 >= n | 2i > n |
index: 0 1 2 3 4 5
value: A B C D E F
A(0)
/ \
B(1) C(2) children of 1: 2·1+1 = 3, 2·1+2 = 4
/ \ /
D(3) E(4) F(5) parent of 5: ⌊(5-1)/2⌋ = 2Two other encodings are worth knowing. A parent array (parent[i] for each node) is all Union-Find (Disjoint Set) needs. LeetCode serializes trees in level order with nulls, so our running example is written [1, 2, 3, 4, 5, null, 6, null, null, 7].
Thinking recursively: height, size and diameter
A binary tree is either empty or a node with a left subtree and a right subtree, and both subtrees are binary trees. That recursive definition gives almost every tree algorithm the same shape: solve the left subtree, solve the right subtree, combine at the node. Because the combine step runs after both children return, this is a post-order traversal (see Tree Traversals).
Diameter: the longest path anywhere
The diameter is the number of edges on the longest path between any two nodes. That path climbs up from one leaf, bends at some highest node, and descends to another. If the path bends at node v, its length is (height(v.left) + 1) + (height(v.right) + 1). So compute heights bottom-up and, at every node, update a running maximum with that bend length.
- 1
Leaves report height 0
Nodes
4,7and6have two empty children (height -1 each). The bend length at a leaf is0. - 2
Node 5
Left child
7has height 0, right is empty (-1). Bend length(0 + 1) + (-1 + 1) = 1. Height of5is 1. - 3
Node 2
Left
4has height 0, right5has height 1. Bend length1 + 2 = 3(the path 4-2-5-7). Height of2is 2. - 4
Node 3
Left is empty, right
6has height 0. Bend length 1. Height of3is 1. - 5
Root 1
Left
2has height 2, right3has height 1. Bend length3 + 2 = 5, the path 7-5-2-1-3-6. The diameter is 5.
Beyond two children
General (n-ary) trees store a list of children per node; file systems, the HTML DOM and JSON documents are all n-ary trees. The left-child, right-sibling trick converts any n-ary tree into a binary tree: the left pointer goes to the first child and the right pointer to the next sibling. Specialized wide trees such as Tries (Prefix Trees) and B-Trees & B+ Trees trade more children per node for a much smaller height.
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Height, size, leaf count | O(n) | O(h) | Every node visited once; stack depth equals height |
| Diameter (single pass) | O(n) | O(h) | Return height, update the best bend length |
| Diameter (height at every node) | O(n²) | O(h) | Worst case on a skewed tree; avoid |
| Search an unordered binary tree | O(n) | O(h) | No ordering means no pruning; BSTs fix this |
| Parent / child lookup in array form | O(1) | O(1) | Index arithmetic on a complete tree |
| Build from level-order list | O(n) | O(n) | Queue holds up to one level of nodes |
h ranges from ⌊log₂ n⌋ for a complete tree to n − 1 for a degenerate one, so O(h) space means O(log n) at best and O(n) at worst.
Implementation
The linked representation plus the three classic recursive measurements. Height counts edges, so the empty tree has height -1.
from typing import Optional
class TreeNode:
def __init__(self, val: int, left: "Optional[TreeNode]" = None,
right: "Optional[TreeNode]" = None):
self.val = val
self.left = left
self.right = right
def height(node: Optional[TreeNode]) -> int:
"""Edges on the longest downward path; the empty tree has height -1."""
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
def size(node: Optional[TreeNode]) -> int:
if node is None:
return 0
return 1 + size(node.left) + size(node.right)
def count_leaves(node: Optional[TreeNode]) -> int:
if node is None:
return 0
if node.left is None and node.right is None:
return 1
return count_leaves(node.left) + count_leaves(node.right)
# 1
# / \
# 2 3
# / \ \
# 4 5 6
# /
# 7
root = TreeNode(1,
TreeNode(2, TreeNode(4), TreeNode(5, TreeNode(7))),
TreeNode(3, None, TreeNode(6)))
print(height(root), size(root), count_leaves(root)) # 3 7 3Key takeaways
- A tree with n nodes has exactly n − 1 edges and one path between any two nodes; a binary tree allows at most two ordered children per node.
- Height ranges from ⌊log₂ n⌋ (complete) to n − 1 (degenerate). Most tree operations cost O(h), so the shape decides the speed.
- A perfect tree of height h holds 2^(h+1) − 1 nodes; complete trees fill levels left to right and live in an array with children at
2i + 1and2i + 2. - Most binary-tree problems are solve left, solve right, combine: height, size, diameter and balance checks are each a single post-order pass.
- Compute derived values bottom-up in one pass instead of calling a helper from every node, which silently turns O(n) into O(n²).
Common pitfalls
- Mixing height conventions: counting nodes in the base case (
return 0) and edges elsewhere produces off-by-one answers. - Assuming the diameter passes through the root. In a tree with a deep, bushy left subtree and a tiny right subtree, it does not.
- Calling
height()inside a recursion that already visits every node, which costs O(n²) on skewed input. - Using the array representation for sparse or skewed trees, where the number of slots grows exponentially with height.
- Forgetting that recursion depth is O(h): deep, unbalanced trees overflow the call stack in Python and Java.
Interview tips
- State your height convention (edges or nodes) and the matching empty-tree base case before you write code.
- For any whole-tree property, ask what each child must report so the parent can finish the job, then write one post-order recursion (often returning a pair).
- Quote space complexity as O(h) and add that h can be n on a skewed tree; offer an iterative version if the interviewer worries about depth.
- Know the array index formulas cold: heaps, segment trees and heap sort all rely on them.
Real-world applications
- File systems, the HTML DOM and JSON or XML documents are all rooted trees.
- Compilers build parse trees and abstract syntax trees; expression trees evaluate arithmetic in post-order.
- Huffman coding builds a full binary tree whose root-to-leaf paths are the compressed bit codes.
- Decision trees and random forests in machine learning split data at each internal node.
- Binary heaps (priority queues) and segment trees store complete binary trees in plain arrays.
Practice problems
Test yourself
How many nodes does a perfect binary tree of height 3 (counting edges) contain?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.