Tree Fundamentals
Understand roots, parents, children, depth, height, and traversal orders. A tree is a graph with enough structure to make many problems much simpler.
Trees is nested under Graphs , so techniques in the broader family usually still apply here.
Interactive visualization
Use the controls to connect the idea to concrete operations before diving into the full write-up.
Trees expose hierarchy directly
Every node except the root has exactly one parent, which makes subtree reasoning much cleaner than on a general graph.
Family
Graphs → Trees
Hierarchies and constrained graphs. A tree is a connected acyclic graph.
Builds on
1 topic
Read these first if you want the surrounding context.
Unlocks
13 next topics
Use these follow-ups when you want to apply the current idea in a richer setting.
Learning paths
4
This topic appears in curated progressions so you can keep moving without guessing the next step.
Problem
Many structures and recursive problems are not arbitrary graphs - they are hierarchies. You have a root, smaller subproblems below it, and no cycles tying the structure into knots.
That is the world of trees.
Intuition
A tree is a graph with exactly the constraints you want for hierarchical reasoning:
- it is connected
- it has no cycles
Those two facts buy you a lot:
- there is exactly one simple path between any two nodes
- every node except the root has exactly one parent
- each node owns a clean subtree that can be solved recursively
This is why trees feel friendlier than general graphs. The structure removes a huge class of edge cases.
Core vocabulary
- Root: the chosen starting node
- Parent / child: direction induced by rooting the tree
- Leaf: a node with no children
- Depth: distance from the root
- Height: longest downward path to a leaf
- Subtree: a node plus everything below it
Once you see a subtree, you should immediately think: this problem might be recursive.
Structural facts worth memorizing
For a tree with nodes:
- it has exactly edges
- removing any edge splits it into two components
- adding any extra edge creates exactly one cycle
These are not trivia. They are often the shortest route to a proof or to a linear-time solution.
Traversal orders
DFS traversals
DFS on a tree gives the classic recursive orders:
- Pre-order: process node before children
- In-order: process between children (binary trees only)
- Post-order: process after children
Post-order is especially important because it lets children compute answers before the parent combines them.
BFS traversal
BFS on a tree is level-order traversal.
That is how you:
- process the tree level by level
- find minimum depth
- connect siblings or cousins
- serialize by layers
Why trees are easier than graphs
In a rooted tree, you usually do not need a visited set. If you only move from parent to children, the structure itself prevents revisits.
Compare that to a general graph where cycles force you to track visited nodes explicitly.
This is the practical meaning of “tree = special case of graph”: many graph algorithms simplify because the shape is stricter.
Common patterns
Subtree aggregation
Ask each subtree for an answer, then combine.
Examples:
- subtree size
- height / diameter
- sum of values
- balanced-tree checks
Choose-before / choose-after
Many tree DP problems come down to whether the current node’s answer depends on:
- the answer before visiting children
- the answer after visiting children
That is just another way of asking which traversal order you need.
Implicit trees
Backtracking problems often build an implicit tree of decisions:
- pick / skip
- place / remove
- continue / prune
Even when there is no tree in memory, the search space behaves like one.
Complexity
| Task | Time | Space |
|---|---|---|
| DFS traversal | recursion stack | |
| BFS traversal | queue, where is max width | |
| Visit every node once | depends on traversal |
Here is the height of the tree. Balanced trees have ; chains have .
Key takeaways
- A tree is a connected acyclic graph, which gives you unique paths and clean parent/child structure
- Subtrees are self-contained subproblems, so recursive reasoning is the default mental model
- DFS is best when you need subtree answers; BFS is best when you need level-by-level structure
- Many graph headaches disappear on trees because the structure prevents cycles and repeated visits
- BSTs, heaps, tries, and segment trees are all specialized trees that add one more invariant on top of the basic tree shape
Practice problems
| Problem | Difficulty | Key idea |
|---|---|---|
| Maximum Depth of Binary Tree | 🟢 Easy | Tree height is the simplest subtree aggregation |
| Binary Tree Level Order Traversal | 🟡 Medium | BFS on a tree is level-order traversal |
| Diameter of Binary Tree | 🟡 Medium | Combine subtree heights bottom-up |
| Balanced Binary Tree | 🟢 Easy | Post-order traversal with early failure |
| Lowest Common Ancestor of a Binary Tree | 🟡 Medium | Recursively merge information from left and right subtrees |
Relation to other topics
- Graph fundamentals is the broader theory; trees are graphs with extra guarantees
- BFS and DFS become tree traversals when the graph has no cycles
- Binary search tree, heap, trie, and segment tree each add a different invariant on top of the tree shape
- Backtracking explores an implicit tree of decisions, even when the original problem is not presented as one
Build on these first
These topics supply the mental model or underlying structure that this page assumes.
What this enables
Once the current idea feels natural, these are the most useful next jumps.
Binary Search Tree (BST)
A sorted tree structure enabling O(log n) search, insert, and delete. Foundation for balanced trees, sets, and maps.
Heap & Priority Queue
A complete binary tree where every parent is smaller (or larger) than its children. The backbone of Dijkstra, event scheduling, and top-k problems.
Binary Lifting
Jump upward in a rooted tree by powers of two to answer k-th ancestor and many LCA-style queries quickly.
Euler Tour Technique
Flatten a rooted tree into an array so subtree problems become range problems. This is the bridge between trees and range-query structures.
Heavy-Light Decomposition
Break tree paths into O(log n) heavy-chain segments so path queries can ride on top of a segment tree instead of walking edge by edge.
Lowest Common Ancestor
Find the deepest shared ancestor of two nodes in a rooted tree. LCA is a core tree-query problem that ties together DFS, binary lifting, and Euler tours.
Related directions
These topics live nearby conceptually, even if they are not direct prerequisites.
BFS — Breadth-First Search
Explore a graph level by level using a queue. BFS finds the shortest path in unweighted graphs and is fundamental to many graph algorithms.
DFS — Depth-First Search
Dive as deep as possible before backtracking. DFS is essential for detecting cycles, topological sorting, and exploring all paths in a graph.
0-1 BFS
Find shortest paths in graphs whose edge weights are only 0 or 1 using a deque instead of a heap.
Union-Find (Disjoint Set)
Track connected components efficiently with near-constant time union and find operations. The backbone of Kruskal's MST and dynamic connectivity.
More from Trees
Stay in the same family when you want parallel variations of the same mental model.
Binary Search Tree (BST)
A sorted tree structure enabling O(log n) search, insert, and delete. Foundation for balanced trees, sets, and maps.
Heap & Priority Queue
A complete binary tree where every parent is smaller (or larger) than its children. The backbone of Dijkstra, event scheduling, and top-k problems.
Binary Lifting
Jump upward in a rooted tree by powers of two to answer k-th ancestor and many LCA-style queries quickly.
Euler Tour Technique
Flatten a rooted tree into an array so subtree problems become range problems. This is the bridge between trees and range-query structures.
Paths that include this topic
Follow one of these sequences if you want a guided next step instead of open-ended browsing.
Graph toolkit
Start with graph shape, then layer traversal, connectivity structure, and both single-source and all-pairs path algorithms.
Ordered structures
See how order can come from sorted arrays, search trees, skip lists, disk-friendly indexes, heaps, and prefix trees.
Rooted tree queries
Flatten subtrees, jump through ancestors, and break tree paths into array segments instead of climbing naively.
Tree path queries
Build the full ladder from ancestor queries to heavy-light decomposition and historical segment trees.
From the blog
Pair the atlas with recent writing from the rest of the site when you want a broader engineering perspective alongside the topic graph.