</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

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.

flowchart TD A["Pick a visiting order"] --> B["Walk every node once"] B --> C["Do work at each node"] C --> D["Combine answers from children"]

๐Ÿ’ก 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).

Recursive template: the same function recurses on the left and right subtrees


The five problems and how they connect

Five problems mapped onto one template: Traverse (Preorder/Inorder/Postorder, Inorder Successor) and Compare (Same Tree)

Traversals โ€” the same walk, three timings

The three depth-first orders differ by one thing: when you record the node relative to its children.

Three traversals of one tree: Preorder (R,L,Ri), Inorder (L,R,Ri) gives sorted order on a BST, Postorder (L,Ri,R)

  • 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:

  1. 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.
  2. 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 Inorder Traversal

Core idea: Walk left subtree โ†’ node โ†’ right subtree recursively, and for a binary search tree this single rule spits out every key in sorted order.

Problem, rephrased

You're handed the root of a binary tree. Each node holds an integer. Produce the list of values you'd collect if you visited the left subtree first, then the node itself, then the right subtree โ€” applied recursively at every node. That ordering has a name: inorder.

Concretely: imagine an org chart where each manager has at most a "junior report" (left) and a "senior report" (right). Inorder means "report up everyone junior-side first, then yourself, then the senior-side chain." For a binary search tree (left < node < right), this is exactly the rule that prints the whole tree in ascending order โ€” which is why this tiny problem is the backbone of every ordered iterator you've ever used.

Input (tree) Inorder output Why
empty tree [] nothing to visit
single node 5 [5] left empty, visit 5, right empty
BST [2,1,3] (root 2, kids 1 and 3) [1, 2, 3] sorted!
[1,null,2,3] (right-leaning) [1, 3, 2] visit 1, then in right subtree: 3 then 2

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

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.