All articles
· 12 min deep-divedata-structuresalgorithms
Article 1 in your session

Trees — Hierarchies, Traversals, and Balanced Search

A scroll-driven visual deep dive into tree data structures. Binary trees, BSTs, AVL trees, heaps, and B-trees — with real-world applications in databases, file systems, priority queues, and decision engines.

Introduction 0%
Introduction
🎯 0/4 0%

🌳

Hierarchies everywhere.
O(log n) guaranteed.

Trees model hierarchical relationships: file systems, HTML DOM, org charts, compiler parse trees, and database indexes. A balanced binary search tree gives O(log n) search, insert, and delete — even in the worst case. From AVL trees to B-trees to heaps, understanding trees unlocks the entire spectrum of efficient data organization.

↓ Scroll to see how trees organize the world’s data

Binary Tree Basics

Binary Trees: Nodes With At Most Two Children

10root5152leaf7leaf12leaf20leafIn-order:2, 5, 7, 10, 12, 15, 20← sorted! (BST property)
A binary tree with 7 nodes: root, internal nodes, and leaves

Four tree traversal orders

📑 In-Order

Visit left subtree, then root, then right subtree. For BSTs, this produces elements in sorted order — making it the go-to traversal for ordered output.

Left → Root → Right: 2, 5, 7, 10, 12, 15, 20
📋 Pre-Order

Visit root first, then left and right subtrees. Useful for copying or serializing a tree — the root comes first so you can reconstruct the structure top-down.

Root → Left → Right: 10, 5, 2, 7, 15, 12, 20
🧹 Post-Order

Visit children first, then root (bottom-up). Ideal for deletion and expression evaluation — you process dependencies before the node that depends on them.

Left → Right → Root: 2, 7, 5, 12, 20, 15, 10
📶 Level-Order (BFS)

Visit every node at depth d before any node at depth d+1, using a queue. This breadth-first approach is essential for finding shortest paths and visualizing tree structure layer by layer.

BFS: 10, 5, 15, 2, 7, 12, 20
↑ Answer the question above to continue ↑
🟢 Quick Check Knowledge Check

In a binary search tree with n nodes, what's the time complexity of finding the minimum element?

BST Property

Binary Search Trees: Order Enables Speed

BST search: binary search on a tree

1
BST invariant: left.val < node.val < right.val (for ALL nodes)
Every node partitions its subtree: everything left is smaller, everything right is larger
2
Search: compare target with current node → go left or right → O(h)
Where h = tree height. For balanced trees, h = log₂(n). For degenerate trees, h = n.
3
Insert: search for the key → when you hit null, insert there → O(h)
Follow the same path as search. The new node always becomes a leaf.
4
Delete: 3 cases → (1) leaf: just remove, (2) one child: replace with child, (3) two children: replace with in-order successor
The in-order successor is the leftmost node in the right subtree. This maintains the BST invariant.
↑ Answer the question above to continue ↑
🟡 Checkpoint Knowledge Check

You insert the keys [1, 2, 3, 4, 5] in order into an empty BST. What does the tree look like, and what's the search time?

Balanced Trees

Self-Balancing Trees: Guaranteed O(log n)

AVL TreeBalance factor:|height(L) - height(R)| ≤ 1Height: ≤ 1.44 log₂(n)Rotations per insert: 1-2✓ Strict balance → fast lookup✗ More rotations on writeBest for:Read-heavy workloadsIn-memory databasesRed-BlackColoring rules:No two red nodes in a rowHeight: ≤ 2 × log₂(n+1)Rotations per insert: 0-2✓ Fewer rotations on write✗ Slightly taller than AVLBest for:Write-heavy workloadsJava TreeMap, C++ std::mapB-TreeMulti-way branching:Up to M children per nodeHeight: log_M(n) — very shortNode = disk page (4KB)✓ Minimizes disk I/O✓ Excellent cache behaviorBest for:Disk-based storagePostgreSQL, SQLite, NTFS
AVL, Red-Black, and B-trees — different balancing strategies for different use cases
↑ Answer the question above to continue ↑
🟡 Checkpoint Knowledge Check

You're building a real-time trading platform that processes 50,000 insert/delete operations per second with occasional lookups. Which self-balancing tree should you use?

Heaps

Heaps: The Priority Queue Engine

Binary heap operations

👑 Heap Property

The fundamental invariant: every parent is smaller (min-heap) or larger (max-heap) than its children. This guarantees the global minimum or maximum is always at the root, accessible instantly.

parent ≤ children (min-heap)
⬆️ Insert (Bubble Up)

Add the new element at the end of the array (bottom of the tree), then repeatedly swap it with its parent until the heap property is restored. At most log n swaps needed.

O(log n)
⬇️ Extract Min/Max (Bubble Down)

Remove the root (the min or max), replace it with the last leaf, then sift it down by swapping with the smaller (or larger) child until the heap property holds again.

O(log n)
👀 Peek

Simply return the root element — no modifications needed. The heap property guarantees the extreme value is always sitting at index 0.

O(1)
🏗️ Build Heap

Surprisingly efficient: build a heap from an unsorted array in linear time using bottom-up heapify. Nodes near the bottom (most of them) barely move, making the total work O(n), not O(n log n).

O(n) bottom-up heapify
1i=03i=15i=27i=39i=48i=510i=6Array representation:1[0]3[1]5[2]7[3]9[4]8[5]10[6]parent = ⌊(i-1)/2⌋ • left = 2i+1 • right = 2i+2
Min-heap as a tree and its array representation — parent at i, children at 2i+1 and 2i+2
↑ Answer the question above to continue ↑
🟡 Checkpoint Knowledge Check

You need to find the k-th smallest element in a stream of 100 million numbers. What's the optimal approach?

Real-World Uses

Trees Power Everything

🗄️ Database Indexes• B+ trees: range queries in O(log n)• Every SQL index is a B-tree• LSM trees: write-optimized storagePostgreSQL, MySQL, RocksDB📁 File Systems• Directory hierarchy = tree• NTFS, ext4 use B-trees for dirs• ZFS uses Merkle trees for integrityEvery OS uses tree-based FS🏥 Priority Queues• Dijkstra’s algorithm (min-heap)• Task scheduling (priority heap)• Event-driven simulationKubernetes, hospital triage🌐 Web & Compilers• HTML DOM: tree of elements• AST: compiler parse trees• React Virtual DOM: tree diffingEvery browser, V8, TypeScript
Tree structures are the backbone of databases, operating systems, compilers, and AI

🎓 What You Now Know

Binary trees model hierarchical data — file systems, DOM, org charts. Four traversal orders serve different purposes.

BSTs give O(log n) search — if balanced. Sorted insertion creates O(n) degenerate trees. AVL and Red-Black trees guarantee balance.

B-trees minimize disk I/O — wider branching = shorter height = fewer disk seeks. Every database index is a B-tree.

Heaps power priority queues in O(log n) — stored as arrays with no pointers. Used in Dijkstra’s, task scheduling, and top-k problems.

Trees are the foundation for tries (prefix search), segment trees (range queries), and decision trees (ML). The hierarchy pattern is universal. ⚡

Keep Learning