Skip to content
Chethan Yadav_
Data Structures & Algorithms

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.

TermMeaning
Depth of a nodeEdges from root to the node
Height of a nodeEdges on the longest path down to a leaf
Height of treeHeight of the root
DegreeNumber of children
SubtreeA 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, right

Types of binary trees

TypeDefinition
FullEvery node has 0 or 2 children
CompleteAll levels full except possibly the last, filled left to right (heaps)
PerfectAll internal nodes have 2 children, all leaves at the same level: 2^(h+1) - 1 nodes
BalancedHeights 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

OrderSequenceTypical use
PreorderRoot, Left, RightCopy or serialize a tree
InorderLeft, Root, RightSorted order of a BST
PostorderLeft, Right, RootDelete 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 out

Morris 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 res

All 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.

OperationBalancedSkewed
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)

Deletion cases

  1. Leaf: remove it.
  2. One child: replace the node with its child.
  3. 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:

CaseFix
Left-LeftRight rotation
Right-RightLeft rotation
Left-RightLeft rotation on child, then right rotation
Right-LeftRight 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).

AVLRed-Black
BalanceStricterLooser
LookupsFasterSlightly slower
Inserts and deletesMore rotationsFewer rotations
Used inRead-heavy workloadsJava 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 right

In 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

  • n nodes, n - 1 edges; 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).