Computer Science

The Tree

A hierarchical data structure consisting of nodes connected by edges, with one root node and zero or more subtrees.

Root A B C D E F L L

Key Terminology

🌳

Root

The topmost node. Every tree has exactly one root. It has no parent.

🍃

Leaf

A node with no children. These are the terminal nodes at the bottom of the tree.

📏

Depth & Height

Depth = distance from root. Height = longest path from node to any leaf.

👶

Parent & Child

Each node (except root) has one parent. A node can have zero or more children.

🌲

Subtree

A tree consisting of a node and all its descendants. Every node forms a subtree.

🔗

Edge

The link between a parent and child. A tree with N nodes has exactly N-1 edges.

What Does a Tree Do?

1

Organizes Data Hierarchically

Trees model parent-child relationships naturally — file systems, DOM, organization charts, and more.

2

Enables Fast Search

Binary Search Trees (BST) support O(log n) lookup, insertion, and deletion when balanced.

3

Efficient Traversal

Visit every node systematically via DFS (pre/in/post-order) or BFS (level-order) in O(n).

4

Supports Prefix Matching

Tries (prefix trees) power autocomplete, spell checkers, and IP routing tables.

5

Maintains Sorted Order

Balanced trees (AVL, Red-Black) keep data sorted while supporting dynamic insertions and deletions.

Common Types

Binary Tree

Each node has at most 2 children (left and right).

Max nodes at level d = 2^d

Binary Search Tree (BST)

Left < Parent < Right. Enables O(log n) search.

search(key) → compare & branch

AVL / Red-Black Tree

Self-balancing BSTs that guarantee O(log n) operations.

Balance factor ∈ {-1, 0, 1}

Heap

Complete binary tree where parent ≥ children (max-heap).

peek() → O(1), insert → O(log n)

Trie (Prefix Tree)

Each node represents a character. Paths form words.

search(prefix) → O(m), m = len

B-Tree / B+ Tree

Multi-child balanced trees used in databases and file systems.

Used by PostgreSQL, SQLite, NTFS

Time Complexity

Operation Average Worst (unbalanced)
Search O(log n) O(n)
Insert O(log n) O(n)
Delete O(log n) O(n)
Traversal O(n) O(n)

Real-World Use Cases

📁

File Systems

Directories and files form a tree hierarchy.

🌐

HTML / DOM

The browser's Document Object Model is a tree of elements.

🗄️

Database Indexes

B-Trees power SQL indexes for fast row lookups.

🤖

Decision Trees

ML models that classify data through branching decisions.

🔀

Git History

Commits form a directed acyclic graph — a tree-like structure.

📡

Network Routing

IP tries route packets efficiently through prefix matching.