Tree Essentials & Core Mechanics
What is this?
Before doing anything fancy with a tree, you need two everyday skills: how to visit every node in some sensible order, and how to compare two trees or measure one. Think of touring a museum โ you can stroll the rooms in different routes, but you still want to see every exhibit exactly once. These problems teach you those reliable walking routes and the habit of checking each node against its neighbors.
๐ก Fun fact: The three classic walking orders โ preorder, inorder, and postorder โ were named by Donald Knuth, who literally wrote the book on these algorithms. On a sorted tree, the "inorder" walk magically spits the values out in perfect sorted order.
๐ The 5 problems in this chapter are free. Sign in with Google or Microsoft to start solving.
Core idea: Before you can solve a clever tree problem, you need two boring superpowers cold: walking a tree in a chosen order and comparing/measuring it node-by-node. This chapter drills exactly those โ and they turn out to be the building blocks every harder tree problem snaps together from.
What this chapter is really teaching
A binary tree is recursive by definition โ empty, or a node with a left and a right subtree. So the foundational skill isn't memorizing problems; it's getting fluent with the one template that fits the recursive shape:
def solve(node):
if not node: # 1. base case โ the empty tree
return ... # (almost every bug hides in a missing base case)
L = solve(node.left) # 2. trust recursion on the smaller trees
R = solve(node.right)
return combine(node, L, R) # 3. do this node's work, fold the results
Three slots: a base case, two recursive calls, and a combine step. Everything in this chapter is a variation on where you do the node's work (the order) and what the combine step computes (a list, a boolean, a number).
The five problems and how they connect
Traversals โ the same walk, three timings
The three depth-first orders differ by one thing: when you record the node relative to its children.
- Binary Tree Preorder Traversal โ root-first. The natural order for cloning and serializing a tree. (recursive โ explicit stack โ Morris O(1) space)
- Binary Tree Inorder Traversal โ left-root-right. On a BST this streams keys in sorted order โ the backbone of an ordered index scan. (recursive โ stack โ Morris)
- Binary Tree Postorder Traversal โ children-before-parent. The order for deletion, bottom-up sizes, and Merkle hashing. (recursive โ flag-stack โ reversed-preorder trick)
- Binary Tree Inorder Successor โ "what's the next node in inorder order?" โ i.e. advancing a sorted cursor one step, the way a database index walks to the next key.
Comparison โ fold the tree into a yes/no
- Same Tree โ walk two trees in lockstep and demand same shape and same value at every position, bailing the instant one disagrees. This is the inner loop of Merkle-tree / replica comparison in distributed databases.
The two cross-cutting skills you'll practice
Recursion vs. iteration (and why both matter)
| Recursion | Explicit stack/queue | |
|---|---|---|
| Reads like | the tree's definition โ elegant | a manual to-do list โ verbose |
| Space | O(h) call stack | O(h) or O(w) your structure |
| Risk | stack overflow on a skewed tree (h = n) |
none โ you control the depth |
| Interview ask | "now do it without recursion" | this is the answer |
Interviewers very often follow "write the recursive version" with "now make it iterative." Practicing the explicit-stack form here is what lets you answer that instantly.
The base case is where bugs live
Every recursion needs an honest answer for the empty tree (None). Most tree bugs are a missing or wrong base case โ a comparison that crashes on a null child, a traversal that double-counts a leaf. Build the reflex: write if not node first, decide what it returns, then write the rest.
๐ Draw it yourself
Two quick sketches make this whole chapter click:
- The three orders, one tree. Draw a tiny tree
(R) โ (L),(Ri)three times. On copy 1 number the nodes in preorder visit order, copy 2 in inorder, copy 3 in postorder. Seeing 1-2-3 land in different spots burns the difference in permanently. - Lockstep comparison. Draw two trees side by side and walk a finger down both at once for Same Tree โ mark the first position where they'd disagree. That's the early-exit your code performs.
Snap photos of your sketches and embed them in any lesson with the /host-diagrams skill.
Complexity at a glance
| Operation | Time | Space | Note |
|---|---|---|---|
| Any traversal (recursive/stack) | O(n) | O(h) | Visit each node once |
| Morris traversal | O(n) | O(1) | Reuse null right-pointers |
| Same Tree comparison | O(n) | O(h) | Early-exit on first mismatch |
| Inorder successor (BST walk) | O(h) | O(1) | No need to materialize the full order |
Key takeaways
- One template, many problems. Base case โ recurse left/right โ combine. Get this reflex and traversal, comparison, and successor all fall out of it.
- The three DFS orders differ only in when you touch the node โ preorder copies, inorder sorts (on a BST), postorder cleans up.
- Always be ready to go iterative. The explicit-stack form is the standard follow-up; Morris is the "O(1) space" flex.
- Master the base case. Empty-tree handling is where most tree bugs (and most interview points) are won or lost.
- Why this chapter matters: these aren't five trivia problems โ they're the moving parts that every later tree problem (LCA, completeness, serialize) is assembled from.
Next: start with the three traversals, then Same Tree โ then carry the template into the harder problems in this topic.
Binary Tree Preorder Traversal
Core idea: Visit yourself before your children โ emit the root, then recurse left, then right โ so the output reads top-down, parents before descendants.
Problem, rephrased
You're handed the root of a binary tree. Walk it in preorder โ Root โ Left โ Right โ and return the list of values in the exact order you visited them.
Forget abstract nodes for a second. Imagine you run a small cloud team and you keep your service-deployment plan as a tree. The plan's root is the region you deploy first; each node's left child is its primary failover target and the right child is the secondary. When you print the rollout order, you always announce a node before the targets that depend on it โ because nobody can fail over to a region that hasn't been brought up yet. That "announce the parent first, then walk into its dependents" rule is preorder.
Here's that same tree as data:
| Input (tree) | Preorder output |
|---|---|
us-east โ (us-west โ ap-south, eu-west) |
[us-east, us-west, ap-south, eu-west] |
empty tree (root = None) |
[] |
single node [42] |
[42] |
The output always starts with the root and never visits a child before its parent.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson