DSA/Lesson 6 of 11/6 min read
Trees
Binary trees, traversals, binary search trees, balanced trees like AVL and red-black, lowest common ancestor and segment trees.
On this page
Tree basics
A tree is a connected acyclic graph with a single root. Each node has zero or more children; nodes without children are leaves.
| Term | Meaning |
|---|---|
| Depth of a node | Edges from root to the node |
| Height of a node | Edges on the longest path down to a leaf |
| Height of tree | Height of the root |
| Degree | Number of children |
| Subtree | A node plus all its descendants |
A tree with n nodes has exactly n - 1 edges.
Binary Tree
Each node has at most two children: left and right.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, rightTypes of binary trees
| Type | Definition |
|---|---|
| Full | Every node has 0 or 2 children |
| Complete | All levels full except possibly the last, filled left to right (heaps) |
| Perfect | All internal nodes have 2 children, all leaves at the same level: 2^(h+1) - 1 nodes |
| Balanced | Heights of left and right subtrees differ by at most 1 at every node |
| Degenerate (skewed) | Every node has one child; behaves like a linked list |
Tree Traversal
Depth-first traversals
| Order | Sequence | Typical use |
|---|---|---|
| Preorder | Root, Left, Right | Copy or serialize a tree |
| Inorder | Left, Root, Right | Sorted order of a BST |
| Postorder | Left, Right, Root | Delete a tree, evaluate expression trees |
def inorder(node, out):
if not node:
return
inorder(node.left, out)
out.append(node.val)
inorder(node.right, out)Inorder Traversal without recursion
def inorder_iter(root):
out, stack, cur = [], [], root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
out.append(cur.val)
cur = cur.right
return outMorris traversal does inorder in O(1) extra space by temporarily threading right pointers.
Level Order Traversal
Breadth-first using a queue. Used for level-by-level problems: right side view, zigzag order, minimum depth.
from collections import deque
def level_order(root):
if not root:
return []
res, q = [], deque([root])
while q:
level = []
for _ in range(len(q)):
node = q.popleft()
level.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
res.append(level)
return resAll traversals are O(n) time. DFS uses O(h) space, BFS uses O(w) where w is the max width.
Binary Search Tree (BST)
A BST keeps the invariant: every value in the left subtree is less than the node, and every value in the right subtree is greater.
| Operation | Balanced | Skewed |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
Deletion cases
- Leaf: remove it.
- One child: replace the node with its child.
- Two children: replace the value with the inorder successor (smallest in right subtree), then delete the successor.
Validating a BST
Pitfall: checking only left.val < node.val < right.val is wrong. Pass down a valid range (low, high) instead, or check that the inorder traversal is strictly increasing.
Balanced trees
Inserting sorted data into a plain BST creates a skewed tree. Self-balancing trees keep height O(log n).
AVL Tree
Strictly balanced: the balance factor (left height minus right height) is -1, 0 or 1 at every node. After insert or delete, fix imbalance with rotations:
| Case | Fix |
|---|---|
| Left-Left | Right rotation |
| Right-Right | Left rotation |
| Left-Right | Left rotation on child, then right rotation |
| Right-Left | Right rotation on child, then left rotation |
Red-Black Tree
Looser balance: each node is red or black, the root is black, no two reds in a row, and every root-to-leaf path has the same number of black nodes. Height is at most 2 log(n + 1).
| AVL | Red-Black | |
|---|---|---|
| Balance | Stricter | Looser |
| Lookups | Faster | Slightly slower |
| Inserts and deletes | More rotations | Fewer rotations |
| Used in | Read-heavy workloads | Java TreeMap, C++ std::map, Linux CFS |
For disk-based indexes, databases use B-trees instead; see indexing.
Lowest Common Ancestor
The deepest node that is an ancestor of both p and q.
def lca(root, p, q):
if not root or root is p or root is q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
return root if left and right else left or rightIn a BST it is simpler: walk down; if both values are smaller go left, if both larger go right, otherwise you are at the LCA. For many queries, use binary lifting (O(log n) per query).
Segment Tree
Answers range queries (sum, min, max) and point or range updates in O(log n) each, using O(n) space (array of size 4n). Each node stores the aggregate of a segment; children split it in half. Lazy propagation supports range updates.
Fenwick Tree
Binary Indexed Tree: prefix sums with point updates in O(log n), using a single array and the trick i & -i to jump between responsible ranges. Simpler and smaller than a segment tree but only for invertible operations like sum.
Classic problems
- Maximum depth:
1 + max(depth(left), depth(right)). - Diameter: at each node,
left_height + right_height; track the global max. - Symmetric tree, same tree, subtree of another tree.
- Serialize and deserialize with preorder plus null markers.
- Construct a tree from preorder and inorder arrays.
- Kth smallest in a BST: inorder traversal, stop at k.
Quick revision
nnodes,n - 1edges; complete trees are stored in arrays (heaps).- Preorder root first, inorder root middle (sorted in BST), postorder root last; BFS uses a queue.
- BST ops are
O(h):O(log n)balanced,O(n)skewed. - Validate a BST with min and max bounds, not just parent-child checks.
- AVL is strictly balanced with rotations; red-black is looser and used by standard libraries.
- LCA: recurse; node is the answer when p and q are found on different sides.
- Segment tree and Fenwick tree handle range queries in
O(log n).