INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS
01
00/04
01 / COVER STEP 13 · BINARY TREES
INVARIANT · STEP 13 · DECK 1 OF 3
WALK THE TREE

A binary tree is just a node holding a value and two pointers, left and right. Nothing else is in the data structure. Everything you do to a tree after that is a traversal: a fixed order for visiting every node. This deck starts from the node itself, then teaches the four walks: preorder, inorder, postorder (one recursion, with a single line moved) and level order (a queue). Then every iterative, stack-based version an interviewer will ask you for. Each walk runs live on an SVG tree that numbers the nodes in visit order, with the call stack or queue right beside it.

4Problems
2Families
12Units
12Live walks
← → ↑ ↓  or  W A S D  navigate SPACE next   DOUBLE-CLICK to advance I index   G goto problem   P predict H hide solutions   T close video   F fullscreen
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
02 / START HERE READ THIS ONE FIRST

HOW THIS DECK WORKS

This is not a list of problems. It is 12 learning units, and every one runs the same four beats. Go in order and the problems stop feeling random.

ASSUMEDA stack and a queue from unit 07 onward. LIFO and FIFO. Stacks & Queues is step 09 and not built yet.

01 INTROWhat the concept is, and what to watch for
02 VIDEOThe lecture, full-width in theatre mode
03 DRILLS2–4 questions checking the lecture landed
04 PROBLEMSThe sheet problems that concept unlocks

Moving around

← ↑Back a slide — or A / W → ↓Forward — or D / S / Space 2×clickDouble-click the right side to advance, left to go back. A single click never moves the deck. IThe index: every problem, clickable, with your progress GJump straight to a problem by its number FFullscreen

While you study

HHide solutions — blurs code and steps so you try first PPredict mode: call the next step before the animation plays it TClose the video — Esc works too ☐ ★Mark solved, or star to revisit. Both are saved automatically.

4 PROBLEMS · EVERY ONE LINKS TO LEETCODE TO SOLVE

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
03 / INDEX PRESS I FROM ANYWHERE

INDEX — ALL 4 PROBLEMS

Click any problem to jump straight to it. Solved ones turn green. Press I from anywhere to come back here. The number is the sheet's row, not your position — the deck teaches in the order that builds, so you will meet them slightly out of numerical sequence.

DFS TRAVERSALS · 03
BFS TRAVERSAL · 01
SOLVED HAS A LEETCODE LINK
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
04 / SIGNALS WHEN YOU SEE X, REACH FOR Y

WHICH TRAVERSAL, AND WHY

Trees are all traversal. The skill is picking the right one. The cards are the phrase in a problem that selects it: “parent before child”, “sorted”, “bottom-up”, “by level”. Get this reflex and deck 2 writes itself.

“COPY / SERIALIZE / PARENT BEFORE CHILD”

record a node the moment you reach it, then its subtrees

PREORDER (root → left → right)O(n)
“SORTED VALUES” / ANYTHING ON A BST

left subtree, then the node, then right, emits BST values in order

INORDER (left → root → right)O(n)
“CHILDREN BEFORE PARENT” / BOTTOM-UP / HEIGHTS / DELETE

both subtrees first, then the node. The node's answer needs its children's

POSTORDER (left → right → root)O(n)
“LEVEL BY LEVEL” / “BY DEPTH” / SHORTEST HOPS

a queue, front-out back-in; the queue holds exactly one frontier

LEVEL ORDER · BFSO(n)
“DO IT ITERATIVELY” / NO RECURSION

replace the call stack with an explicit stack you push and pop yourself

ITERATIVE TRAVERSAL · STACKO(n) time · O(h) space
“GROUP NODES BY LEVEL” (zig-zag, right view, widths)

BFS, but process the queue in size-batches. One batch is one level

LEVEL-BATCHED BFSO(n)
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
05 / CONSTRAINTS BEFORE YOU WRITE A LINE

READ THE ANSWER OFF THE CONSTRAINTS

Almost every tree problem is one O(n) traversal: visit each node once. The number to watch isn't time, it's recursion depth. O(h) space, which is O(n) on a skewed tree and can overflow the call stack.

n ≤
BUDGET
WHAT THAT BUYS YOU
n ≤ 10³
O(n²)
compare every pair of nodes, or re-traverse per node, fine for tiny trees
n ≤ 10⁵
O(n)
ONE traversal visits every node once, the home row for almost every tree problem
n ≤ 10⁶
O(n)
still one linear pass; watch recursion DEPTH, since a skewed tree is O(n) stack frames
height h
O(h) space
recursion (or an explicit stack) uses O(h): O(log n) if balanced, O(n) if skewed
complete tree
O(log²n)
exploit structure, a complete tree's node count needs no full traversal (deck 3)

TREE PROBLEM ⇒ ONE O(n) TRAVERSAL · MIND THE O(h) RECURSION DEPTH

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
06 / ROADMAP WHAT YOU ARE ABOUT TO DO

THE WHOLE RUN, 12 UNITS

Twelve units. First the tree itself (what it is, how it's stored), then the four traversals on the live SVG tree, then every iterative, stack-based version an interviewer asks for. Only four LC problems here. The value is the traversals, which deck 2 builds everything on.

UNIT 01

Trees & Their Types

▶ 9:502 DRILLSNO SHEET ROW
UNIT 02

Representing a Tree

▶ 4:432 DRILLSNO SHEET ROW
UNIT 03

The Four Traversals

▶ 9:592 DRILLSNO SHEET ROW
UNIT 04

Preorder

▶ 7:292 DRILLS1 PROBLEM
UNIT 05

Inorder

▶ 7:072 DRILLS1 PROBLEM
UNIT 06

Postorder

▶ 5:312 DRILLS1 PROBLEM
UNIT 07

Level Order (BFS)

▶ 8:572 DRILLS1 PROBLEM
UNIT 08

Iterative Preorder

▶ 6:502 DRILLSNO SHEET ROW
UNIT 09

Iterative Inorder

▶ 11:142 DRILLSNO SHEET ROW
UNIT 10

Iterative Postorder · 2 Stacks

▶ 4:092 DRILLSNO SHEET ROW
UNIT 11

Iterative Postorder · 1 Stack

▶ 12:332 DRILLSNO SHEET ROW
UNIT 12

All Three in One Pass

▶ 10:572 DRILLSNO SHEET ROW
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
07 / WARMUP LOAD THE TRAVERSAL INSTINCT

ONE RECURSION, THREE ORDERS · STACK VS QUEUE

DRILL 01 · RECALL

A tree recursion makes two calls:
go(node->left)
go(node->right)
Now you add one more line, record(node). How many different places can it sit?

Three slots, so three traversals. Two calls split the function into three gaps: before the first, between the two, after the second. Drop record into each gap and you get three different visit orders, and notice the calls themselves never moved. Units 04 to 06 put a name to each position. Don't learn the names yet. You just counted the slots yourself, and the counting is the part worth having.

DRILL 02 · RECALL

Level order reads the tree row by row. Why does a queue give you that, when a stack does not?

FIFO drains one level before it touches the next. Push the root, then keep popping the front and pushing that node's children to the back. First in, first out, so every node of the current level leaves before any of their children do. That is exactly level by level, left to right. A stack is LIFO, so it would dive to the bottom instead. Deep or wide is decided by nothing more than which end you take from.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
08 / INTRO UNIT 01 · Trees & Their Types

UNIT 01 — Trees & Their Types

A tree is a set of nodes connected with no cycles. A binary tree adds one restriction: every node gets at most two children, a left and a right. That's it. The vocabulary you'll use constantly: the root sits on top and has no parent, a leaf has no children, depth is how far a node sits below the root, and height is how far the furthest leaf sits below the node. Depth and height are measured from opposite ends. Worth getting straight now, because that mix-up is where the off-by-one bugs in deck 2 come from. The named shapes matter later, each one because some algorithm exploits it: full (every node has 0 or 2 children), complete (filled left to right), perfect (every leaf at the same depth), balanced (height stays O(log n)) and BST (ordered).

THE QUESTION THIS LECTURE ANSWERS

WHAT EXACTLY IS A BINARY TREE, AND WHAT ARE ITS NAMED SHAPES?

node = val + left + rightroot · leafheight vs depthfull / complete / perfectbalanced · BST
WHAT TO WATCH FOR
  • 01EVERY NODE HAS ≤ 2 CHILDREN: left AND right (EITHER MAY BE null)
  • 02ROOT = TOP (NO PARENT) · LEAF = NO CHILDREN
  • 03HEIGHT = LONGEST PATH DOWN TO A LEAF · DEPTH = DISTANCE FROM ROOT
  • 04FULL · COMPLETE · PERFECT · BALANCED · BST. THE SHAPES THAT GET EXPLOITED LATER
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
09 / VIDEO UNIT 01 · Trees & Their Types

L1. Introduction to Trees | Types of Trees

STRIVER A2Z
Trees & Their Types
RUNTIME 9:50
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
10 / DRILL UNIT 01 · Trees & Their Types

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

Complete and perfect. What is the actual difference?

Perfect is the strict one, complete is the practical one. Perfect means every level is filled, right to the bottom, exactly 2ʰ⁺¹ − 1 nodes for height h. Complete lets the last level be partial, but it must fill from the left with no gaps. That shape is not a technicality: it is what a binary heap is stored as, and it is why Count Complete Tree Nodes (deck 3) can be done in O(log²n) instead of O(n).

DRILL 02 · RECALL

Same node. What is the difference between its height and its depth?

Height looks down, depth looks up. A node's height is the distance to the deepest leaf below it. Its depth is the distance to the root above it. So the root's height is the whole tree's height while its depth is 0, and a leaf is the other way round with height 0. Same node, two numbers, measured in opposite directions, mixing them up is the classic off-by-one in Maximum Depth and Diameter (deck 2).

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
11 / MECHANISM UNIT 01 · ANATOMYBT · CODE MIRRORED

EVERY WORD HERE IS A PROPERTY OF THE PICTURE

Vocabulary, but each term is something you can point at rather than memorise. The one worth pausing on is depth against height: depth counts edges down from the root, height counts edges down to the furthest leaf, so a leaf has height 0 while the root has the height of the whole tree. They are measured from opposite ends, and swapping them is the most common slip in this deck.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
12 / INTRO UNIT 02 · Representing a Tree

UNIT 02 — Representing a Tree

In code, a node is a value plus two pointers, left and right, and each pointer either points at a child or is null. You hold the whole tree with a single pointer to the root, and from there you can reach every node by following left and right. A missing child is null. A leaf is just a node whose left and right are both null. The data structure ends there, everything from here on is about how you walk it.

THE QUESTION THIS LECTURE ANSWERS

HOW IS A TREE ACTUALLY STORED, AND WHAT IS A null CHILD?

struct Nodeval + left + rightroot pointernull childleaf
WHAT TO WATCH FOR
  • 01A NODE = { val, Node* left, Node* right } (POINTERS, NOT COPIES)
  • 02THE TREE IS ONE POINTER TO THE ROOT; FOLLOW left/right TO REACH ANY NODE
  • 03A MISSING CHILD IS null. THAT'S THE RECURSION'S BASE CASE
  • 04A LEAF HAS BOTH left AND right == null
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
13 / VIDEO UNIT 02 · Representing a Tree

L2. Binary Tree Representation in C++

STRIVER A2Z
Representing a Tree
RUNTIME 4:43
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
14 / DRILL UNIT 02 · Representing a Tree

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

Nearly every recursive tree function opens with if (node == nullptr) return ...;. Why?

null is the base case. A missing child is a null pointer, so the recursion bottoms out on its own the moment it steps onto one. You don't have to invent a stopping rule. The guard does two jobs at once: it stops you dereferencing null, and it declares what an empty subtree is worth (nothing to a traversal, 0 to a height, and so on). Leave it out and the very first leaf's null child crashes you.

DRILL 02 · RECALL

How do you check whether a node is a leaf?

Both children null. A leaf is a real node that happens to have left and right both null. Keep that separate from node == null, which says there is no node here at all. The difference is not pedantic, root-to-leaf paths and path sum both hinge on spotting a leaf specifically, not an empty subtree.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
15 / MECHANISM UNIT 02 · REPRESENT · CODE MIRRORED

THE SHAPE CAN BE ARITHMETIC INSTEAD OF POINTERS

The usual node carries two pointers and the shape lives in them. But number a complete tree in level order and the structure becomes arithmetic. The children of index i are at 2i+1 and 2i+2, the parent at (i-1)/2, and not one pointer is stored. The catch is in the word complete. A skewed tree of depth d would reserve 2d slots to hold d nodes.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
16 / INTRO UNIT 03 · The Four Traversals

UNIT 03 — The Four Traversals

Everything you do to a tree is a traversal, a fixed order for visiting every node exactly once. There are two families. DFS (depth-first) goes all the way down one subtree before it starts the next, and it comes in three flavours depending on when you record the node: preorder (before its children), inorder (between them), postorder (after both). BFS (breadth-first), also called level order, sweeps the tree row by row using a queue. DFS runs on a stack. Usually the call stack. BFS runs on a queue. Learn these four properly and the rest of the topic is just combining them.

THE QUESTION THIS LECTURE ANSWERS

WHAT ARE THE FOUR WAYS TO VISIT EVERY NODE?

traversalDFS: pre / in / postBFS: level orderstack vs queuedeep vs wide
WHAT TO WATCH FOR
  • 01DFS (STACK/RECURSION): PREORDER · INORDER · POSTORDER
  • 02THEY DIFFER ONLY IN WHEN THE NODE IS RECORDED (PRE/IN/POST ITS CHILDREN)
  • 03BFS (QUEUE): LEVEL ORDER. TOP TO BOTTOM, LEFT TO RIGHT
  • 04DFS GOES DEEP FIRST; BFS GOES WIDE FIRST
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
17 / VIDEO UNIT 03 · The Four Traversals

L4. Binary Tree Traversals | BFS | DFS

STRIVER A2Z
The Four Traversals
RUNTIME 9:59
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
18 / DRILL UNIT 03 · The Four Traversals

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

DFS and BFS on the same tree. What is the structural difference?

A stack dives, a queue fans out. DFS commits to one path all the way down and then backtracks, so its frontier is a stack. BFS holds a whole level at a time, so its frontier is a queue. Both touch every node once, so both are O(n) in time. The memory is where they split: DFS costs O(h), the length of one path, and BFS costs O(width), which is up to O(n) at the bottom level.

DRILL 02 · TRACE

Root 1. Its children are 2 (left) and 3 (right). Under 2 sit 4 and 5.
What is the preorder?

1, 2, 4, 5, 3. Preorder records the node first, so 1 comes out. Then it finishes the entire left subtree before touching the right: record 2, then its left child 4, then its right child 5. Only now does it go to 3. Two of the wrong answers are real walks of this same tree, which is what makes them tempting: 4, 5, 2, 3, 1 is its postorder and 1, 2, 3, 4, 5 is its level order.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
19 / MECHANISM UNIT 03 · FOURORDERS · CODE MIRRORED

ONE WALK, AND A SINGLE LINE MOVES

The overview for the four units that follow. All three DFS orders take the identical walk over the tree, same route, same nodes, reached in the same sequence. The only thing that changes is where the record step sits relative to the two recursive calls: before, between, or after. Level order is the odd one out, because it is not a DFS at all. It is a queue, so it reads row by row instead of branch by branch.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
20 / INTRO UNIT 04 · Preorder

UNIT 04 — Preorder

Preorder is root → left → right: record a node the instant you reach it, then go into its left subtree, then its right. In code that is three lines after the null check. record; go left; go right. Since the parent always comes out before its children, preorder is the natural order for copying or serializing a tree (deck 3): whoever reads your output already has the parent by the time the children arrive. The iterative version swaps the call stack for one you push and pop yourself (unit 08).

THE QUESTION THIS LECTURE ANSWERS

WHAT COMES OUT IF YOU RECORD THE NODE BEFORE ITS CHILDREN?

root → left → rightrecord firstroot is #1serialize orderO(h) stack
WHAT TO WATCH FOR
  • 01ORDER: RECORD THE NODE, THEN LEFT SUBTREE, THEN RIGHT SUBTREE
  • 02THE ROOT IS ALWAYS THE FIRST NODE RECORDED (#1)
  • 03THREE LINES: record(node); preorder(left); preorder(right)
  • 04PARENT BEFORE CHILDREN → THE SERIALIZE/COPY ORDER
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
21 / VIDEO UNIT 04 · Preorder

L5. Preorder Traversal of Binary Tree

STRIVER A2Z
Preorder
RUNTIME 7:29
AFTER THIS → 2 DRILLS · PROBLEM #01
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
22 / DRILL UNIT 04 · Preorder

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

In preorder, when exactly does a node get added to the output?

Straight away, before either child. The record line sits first, right after the null check, so out goes the node, then its whole left subtree, then its whole right subtree. That is why the output always opens with the root, and why it reads as 'a node, followed by everything below it on the left, then everything below it on the right'.

DRILL 02 · TRACE

The mechanism tree: 1 on top, 2 and 3 below it, 4 and 5 under 2, 6 and 7 under 3.
Write out the full preorder.

1, 2, 4, 5, 3, 6, 7. Record 1. Go left into 2 and finish it completely, 2, then 4, then 5. Only then go right into 3. 3, then 6, then 7. The other answers are all real walks of this tree, which is exactly why they look plausible: 4, 2, 5, 1, 6, 3, 7 is the inorder, 4, 5, 2, 6, 7, 3, 1 the postorder, 1, 2, 3, 4, 5, 6, 7 the level order. Press P on the mechanism slide and call each node before it lights up.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
23 / MECHANISM UNIT 04 · PREORDER · CODE MIRRORED

PREORDER. RECORD THE NODE, THEN ITS SUBTREES

Preorder is root → left → right: you record a node the moment you reach it, before going into either subtree. The recursion is three lines. Record, go left, go right, and the call stack on the right is nothing more than the path from the root down to wherever you currently are. Watch the badges land: the root is always #1, and a subtree is numbered completely before its sibling gets started. This is the order you would copy or serialize a tree in, because the parent always comes out ahead of its children.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
24 / PROBLEM #01 · DFS · EASY

Binary Tree Preorder Traversal

EASY dfs ▶ SOLVE ON LEETCODE
SIGNAL — WHAT GIVES IT AWAY

“Return the preorder traversal.” The canonical DFS walk. record the node, then recurse left, then right.

INTUITION

If the node is null, return. Otherwise record its value, then go left, then go right. The call stack does all the bookkeeping for you. The solution is nothing more. The iterative version in unit 08 does the same thing with a stack you push yourself, right child before left.

STEPS
  1. solve(node, out): if node is null, return
  2. out.push_back(node->val) // record BEFORE the children
  3. solve(node->left, out)
  4. solve(node->right, out)
  5. Return out from solve(root, out)
BRUTEO(n) recursive
OPTIMALO(n)
↕ SCROLL
// Preorder: record the node, then left subtree, then right.
void solve(TreeNode* node, vector<int>& out) {
    if (node == nullptr) return;
    out.push_back(node->val);     // PRE: record before children
    solve(node->left, out);
    solve(node->right, out);
}
vector<int> preorderTraversal(TreeNode* root) {
    vector<int> out;
    solve(root, out);
    return out;
}
TIMEO(n)each node visited exactly once
SPACEO(h)recursion depth = tree height h (O(n) worst, O(log n) balanced)
TRAP

Swapping the two recursive calls, or dropping the null check. The calls must stay left then right; swapping them mirrors the traversal. For the iterative version, remember a stack is LIFO, push the right child first so the left pops next, or you'll produce a right-to-left preorder.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
25 / INTRO UNIT 05 · Inorder

UNIT 05 — Inorder

Inorder is left → root → right. It is the preorder recursion with one change: the record line slides down to sit between the two calls, so a node is not recorded until its entire left subtree is done. Same skeleton, completely different output. And here is the property that makes inorder matter: on a binary search tree, inorder hands you the values in sorted ascending order. No fact in this deck gets used more, in the whole BST section.

THE QUESTION THIS LECTURE ANSWERS

WHAT HAPPENS WHEN THE RECORD LINE MOVES BETWEEN THE TWO CALLS?

left → root → rightrecord moved downleftmost is #1BST → sortedO(h) stack
WHAT TO WATCH FOR
  • 01ORDER: LEFT SUBTREE, THEN RECORD THE NODE, THEN RIGHT SUBTREE
  • 02SAME RECURSION AS PREORDER. THE record LINE JUST MOVED DOWN ONE
  • 03THE LEFTMOST NODE IS RECORDED FIRST (#1), NOT THE ROOT
  • 04ON A BST, INORDER OUTPUTS VALUES IN SORTED ORDER
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
26 / VIDEO UNIT 05 · Inorder

L6. Inorder Traversal of Binary Tree

STRIVER A2Z
Inorder
RUNTIME 7:07
AFTER THIS → 2 DRILLS · PROBLEM #02
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
27 / DRILL UNIT 05 · Inorder

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

Why does inorder on a BST come out sorted?

Left-node-right, applied to left < node < right. At every node, inorder emits the smaller side, then the node, then the larger side. Apply that all the way down and the leftmost node. The smallest value in the tree. comes out first, and the rightmost comes out last. Nothing is being sorted here; the order was already in the shape. This is why the answer to validate-BST, kth-smallest and the BST iterator is always 'inorder'.

DRILL 02 · TRACE

Same mechanism tree: 1 on top, 2 and 3 below, 4 and 5 under 2, 6 and 7 under 3.
What is the inorder?

4, 2, 5, 1, 6, 3, 7. Run down to the bottom left first, nothing gets recorded on the way. 4 comes out, then its parent 2, then 2's right child 5. Now the left subtree is finished, so the root 1 goes out, and the right subtree gives 6, 3, 7 the same way. Notice where the root landed: dead centre. This is the signature of inorder.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
28 / MECHANISM UNIT 05 · INORDER · CODE MIRRORED

INORDER. LEFT SUBTREE, THEN NODE, THEN RIGHT

Inorder is left → root → right: a node is not recorded until its entire left subtree is done. One thing moved. The record line now sits between the two calls instead of before them, and the whole visit order changes. Watch which node gets badge #1: the leftmost leaf, not the root. On a binary search tree this order emits the values sorted, and that single fact is why inorder turns up on nearly every problem in the BST section.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
29 / PROBLEM #02 · DFS · EASY

Binary Tree Inorder Traversal

EASY dfs ▶ SOLVE ON LEETCODE
SIGNAL — WHAT GIVES IT AWAY

“Return the inorder traversal.” The same recursion as preorder, with the record line moved between the two recursive calls.

INTUITION

Go left, record the node, go right. The only change from preorder is when you record, after the left subtree instead of before it. On a BST that ordering is what makes the output come out sorted.

STEPS
  1. solve(node, out): if node is null, return
  2. solve(node->left, out) // whole left subtree first
  3. out.push_back(node->val) // IN: record between children
  4. solve(node->right, out)
  5. Return out from solve(root, out)
BRUTEO(n) recursive
OPTIMALO(n)
-// Preorder: record the node, then left subtree, then right.+// Inorder: left subtree, then record the node, then right. void solve(TreeNode* node, vector<int>& out) {     if (node == nullptr) return;-    out.push_back(node->val);     // PRE: record before children     solve(node->left, out);+    out.push_back(node->val);     // IN: record between children     solve(node->right, out); }-vector<int> preorderTraversal(TreeNode* root) {+vector<int> inorderTraversal(TreeNode* root) {     vector<int> out;     solve(root, out);     return out; }
TIMEO(n)each node visited once
SPACEO(h)recursion depth = height h
TRAP

Reordering the recursive calls instead of moving the record line. The two solve(left)/solve(right) calls stay in place; only the record statement moved down one line versus preorder. On a BST this is your sorted-order walk, the most reused fact of the BST section.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
30 / INTRO UNIT 06 · Postorder

UNIT 06 — Postorder

Postorder is left → right → root: a node is recorded only after both its subtrees are finished, so the root always comes last. Same recursion again. The record line has just moved to after both calls. This children-before-parent order is the shape of every bottom-up computation. A node's height, its size, its DP answer are all built out of its children's answers, so the children have to finish first. That is not a preference, it is a dependency, and it is why half of deck 2 turns out to be a postorder wearing a different name.

THE QUESTION THIS LECTURE ANSWERS

WHY DOES BOTTOM-UP WORK FORCE YOU TO RECORD LAST?

left → right → rootrecord lastroot is lastbottom-uptree DP
WHAT TO WATCH FOR
  • 01ORDER: LEFT SUBTREE, RIGHT SUBTREE, THEN RECORD THE NODE
  • 02SAME RECURSION. THE record LINE MOVED TO THE END
  • 03THE ROOT IS ALWAYS RECORDED LAST (#n)
  • 04CHILDREN-BEFORE-PARENT = THE ORDER FOR HEIGHTS, SIZES, DELETE, TREE DP
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
31 / VIDEO UNIT 06 · Postorder

L7. Postorder Traversal of Binary Tree

STRIVER A2Z
Postorder
RUNTIME 5:31
AFTER THIS → 2 DRILLS · PROBLEM #03
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
32 / DRILL UNIT 06 · Postorder

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

Computing a node's height, or deleting a whole tree. Why is postorder the natural fit?

The parent's work needs the children's answers. Height is 1 + max(leftHeight, rightHeight). There is nothing to compute until both children have reported back. Deleting is the same shape for a different reason: free the node first and you have just orphaned two subtrees you can no longer reach. Any 'combine the children's results at the node' computation is a postorder, which is exactly what most of deck 2's DP-style problems are.

DRILL 02 · TRACE

Same tree again: 1 on top, 2 and 3 below, 4 and 5 under 2, 6 and 7 under 3.
What is the postorder?

4, 5, 2, 6, 7, 3, 1. Finish the left subtree completely, 4, 5, and only then their parent 2. Then the right subtree the same way, 6, 7, then 3. The root cannot go until both are done, so 1 is last. The tell reads like this: preorder puts the root first, inorder puts it in the middle, postorder puts it last.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
33 / MECHANISM UNIT 06 · POSTORDER · CODE MIRRORED

POSTORDER. BOTH SUBTREES FIRST, THEN THE NODE

Postorder is left → right → root: a node is recorded only once both its subtrees are complete, so the root is always last. Badge #7 here. Same walk again, with the record line moved after both calls. This children-before-parent order is what you need whenever a node's answer is built out of its children's answers: deleting a tree, heights, sizes, any bottom-up tree DP. Half of deck 2's problems are a postorder in disguise.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
34 / PROBLEM #03 · DFS · EASY

Binary Tree Postorder Traversal

EASY dfs ▶ SOLVE ON LEETCODE
SIGNAL — WHAT GIVES IT AWAY

“Return the postorder traversal.” Same recursion again, with the record line moved to after both recursive calls. The root comes last.

INTUITION

Go left, go right, then record the node. Both subtrees finish before the node does, which is exactly what any bottom-up computation needs. Heights, sizes, deleting a tree. Recursively this is trivial. The iterative versions in units 10 and 11 are the fiddliest traversals in the deck.

STEPS
  1. solve(node, out): if node is null, return
  2. solve(node->left, out)
  3. solve(node->right, out) // both subtrees first
  4. out.push_back(node->val) // POST: record after children
  5. Return out from solve(root, out)
BRUTEO(n) recursive
OPTIMALO(n)
-// Preorder: record the node, then left subtree, then right.+// Postorder: both subtrees, then record the node (root last). void solve(TreeNode* node, vector<int>& out) {     if (node == nullptr) return;-    out.push_back(node->val);     // PRE: record before children     solve(node->left, out);     solve(node->right, out);+    out.push_back(node->val);     // POST: record after children }-vector<int> preorderTraversal(TreeNode* root) {+vector<int> postorderTraversal(TreeNode* root) {     vector<int> out;     solve(root, out);     return out; }
TIMEO(n)each node visited once
SPACEO(h)recursion depth = height h
TRAP

Assuming iterative postorder is as easy as preorder. Recursively it's a one-line move (record after both calls). Iteratively it's the hardest of the four. Either two stacks (reverse a root-right-left walk) or one stack with a 'last visited' pointer (units 10–11). Recognise postorder whenever a node's answer depends on its children's.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
35 / INTRO UNIT 07 · Level Order (BFS)

UNIT 07 — Level Order (BFS)

Level order is breadth-first: go through the tree one level at a time, top to bottom, left to right, using a queue instead of recursion. Push the root. Then keep repeating three things. Pop the front, record it, push its non-null children to the back. Because a queue is FIFO, one whole level is drained before the next one starts. And if you read queue.size() at the top of a round, you know exactly how many nodes this level has, which lets you group nodes by level. That grouping is the trick behind zig-zag, right-side view and every 'by level' problem in deck 2.

THE QUESTION THIS LECTURE ANSWERS

HOW DO YOU SWEEP THE TREE LEVEL BY LEVEL WITH A QUEUE?

BFSqueue FIFOpop-record-pushsize() = level widthfrontier
WHAT TO WATCH FOR
  • 01QUEUE, FIFO: PUSH ROOT; POP FRONT, RECORD, PUSH ITS CHILDREN TO THE BACK
  • 02THE QUEUE HOLDS EXACTLY THE CURRENT FRONTIER (ONE LEVEL)
  • 03READ queue.size() BEFORE A ROUND TO GROUP NODES BY LEVEL
  • 04NO RECURSION, O(n) TIME, O(width) SPACE
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
36 / VIDEO UNIT 07 · Level Order (BFS)

L8. Level Order Traversal of Binary Tree

STRIVER A2Z
Level Order (BFS)
RUNTIME 8:57
AFTER THIS → 2 DRILLS · PROBLEM #04
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
37 / DRILL UNIT 07 · Level Order (BFS)

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

In the level-order loop, which node do you record, and where do its children go?

Pop the front, record that, push its children to the back. Those two ends are what produce strict level-by-level, left-to-right order. Take from one end, add at the other. Record children as you push them instead, or push to the front, and the order breaks quietly, sometimes visiting a node twice.

DRILL 02 · TRACE

You have just popped node 1 and recorded it.
What is in the queue now, and who pops next?

The queue is [2, 3], and 2 pops next. Popping 1 pushed its children 2 and 3 to the back, in that order. FIFO means 2 went in first so 2 comes out first, then 3, which finishes level 1 before anything from level 2 (4, 5, 6, 7) is touched. Toggle P on the mechanism slide and you get asked exactly this.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
38 / MECHANISM UNIT 07 · LEVELORDER · CODE MIRRORED

LEVEL ORDER, BFS, ONE LEVEL AT A TIME, WITH A QUEUE

Level order is breadth-first: top to bottom, left to right, using a queue instead of recursion. Pop the front, record it, push its children to the back. Because a queue is FIFO, everything on one level is processed before anything on the next. watch the queue hold exactly the current frontier and nothing else. Read the queue's size at the start of a round and you have one level isolated, which is what zig-zag, right-side view and almost every 'by level' problem in deck 2 are built on.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
39 / PROBLEM #04 · BFS · MED

Binary Tree Level Order Traversal

MED bfs ▶ SOLVE ON LEETCODE
SIGNAL — WHAT GIVES IT AWAY

“Return the values level by level” (a list per level). 'By level' means breadth-first, a queue, batched by level size.

INTUITION

BFS with a queue. Push the root. Then each round: read the queue size first. That is exactly how many nodes this level has, and pop that many, collecting their values into one level's list and pushing their children for the next round. Repeat until the queue is empty.

STEPS
  1. If root is null, return empty. Push root into queue q
  2. While q not empty: levelSize = q.size(); start a new level list
  3. Repeat levelSize times: pop front, add its val to the level, push its non-null children
  4. Append the level list to the result
  5. Return the result
BRUTEO(n)
OPTIMALO(n)
↕ SCROLL
// BFS; snapshot the level size to group nodes per level.
vector<vector<int>> levelOrder(TreeNode* root) {
    vector<vector<int>> res;
    if (!root) return res;
    queue<TreeNode*> q; q.push(root);
    while (!q.empty()) {
        int levelSize = q.size();          // this level's node count
        vector<int> level;
        for (int i = 0; i < levelSize; i++) {
            TreeNode* node = q.front(); q.pop();
            level.push_back(node->val);    // record the popped front
            if (node->left)  q.push(node->left);
            if (node->right) q.push(node->right);
        }
        res.push_back(level);
    }
    return res;
}
TIMEO(n)each node enqueued and dequeued once
SPACEO(n)the queue holds up to one full level, O(n) for the widest level
TRAP

Reading q.size() inside the inner loop. The size must be snapshotted before the inner loop. It grows as you push children, so reading it live merges the next level into the current one. Also push children to the back and record the front, or the left-to-right order breaks.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
40 / INTRO UNIT 08 · Iterative Preorder

UNIT 08 — Iterative Preorder

Iterative preorder replaces the call stack with a stack you manage yourself. Push the root. Then loop: pop a node, record it, and push its right child first, then its left. A stack is LIFO, so the left child, pushed last. is the one that pops next, and you get root → left → right with no recursion anywhere. That right-before-left push is the whole trick, and this is the easiest of the iterative traversals to get right.

THE QUESTION THIS LECTURE ANSWERS

HOW DO YOU DO PREORDER WITH YOUR OWN STACK INSTEAD OF RECURSION?

explicit stackpush right then leftLIFOno recursionO(h) space
WHAT TO WATCH FOR
  • 01EXPLICIT stack; PUSH ROOT TO START
  • 02LOOP: POP → RECORD → PUSH RIGHT CHILD, THEN LEFT CHILD
  • 03LIFO MEANS LEFT (PUSHED LAST) POPS FIRST → left BEFORE right
  • 04WHY ITERATIVE? AVOIDS O(h) CALL-STACK DEPTH ON SKEWED TREES
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
41 / VIDEO UNIT 08 · Iterative Preorder

L9. Iterative Preorder Traversal | Stack

STRIVER A2Z
Iterative Preorder
RUNTIME 6:50
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
42 / DRILL UNIT 08 · Iterative Preorder

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

Why push the right child before the left?

A stack reverses whatever you give it. You want the left subtree handled first, so the left child has to be sitting on top. The last thing you push is what lands on top, so push right, then left. Do it the other way round and you get a right-to-left preorder, which looks completely reasonable in the output and is wrong.

DRILL 02 · RECALL

The recursive version is shorter. So why write the iterative one at all?

You control the depth. Recursion's memory is the call stack. O(h), which becomes O(n) on a skewed tree shaped like a linked list, and that can blow the system stack. Your own stack lives on the heap, where a few hundred thousand frames is not a problem. The visit order is identical; only the machinery underneath changes. Interviewers ask for it a lot. (Morris traversal in deck 3 takes it all the way down to O(1) space.)

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
43 / MECHANISM UNIT 08 · ITERPRE · CODE MIRRORED

THE RECURSION HID A STACK. THIS ONE IS VISIBLE

Every recursive traversal is already using a stack; you just could not see it. Make it explicit and preorder becomes three lines. Pop, record, push both children. The one detail that matters is the push order, right before left, because a stack reverses what you give it, so pushing right first is what makes left come off first. Watch the stack hold [3, 2] after the root: node 3 sits there untouched for five steps while the entire left subtree is dealt with. That parked node is the recursion's pending call frame.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
44 / INTRO UNIT 09 · Iterative Inorder

UNIT 09 — Iterative Inorder

Iterative inorder is the trickier one. You keep a curr pointer and a stack, and the loop alternates between two moves. First: while curr isn't null, push it and go left. You are running down the left spine, recording nothing. Then, when you cannot go left any further, pop a node, record it, and point curr at its right child. Push all the lefts, then pop-record-go-right. That cycle reproduces left → root → right exactly.

THE QUESTION THIS LECTURE ANSWERS

HOW DO YOU DO INORDER ITERATIVELY WITH A STACK AND A CURSOR?

curr + stackpush all leftspop-record-go-rightleft → root → rightO(h) space
WHAT TO WATCH FOR
  • 01curr POINTER + STACK; NO RECURSION
  • 02GO LEFT AS FAR AS POSSIBLE, PUSHING EVERY NODE
  • 03CAN'T GO LEFT? POP → RECORD → curr = node->right
  • 04REPEAT UNTIL BOTH curr IS null AND THE STACK IS EMPTY
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
45 / VIDEO UNIT 09 · Iterative Inorder

L10. Iterative Inorder Traversal | Stack

STRIVER A2Z
Iterative Inorder
RUNTIME 11:14
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
46 / DRILL UNIT 09 · Iterative Inorder

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

You just popped a node and recorded it. Where does curr go next?

curr = popped->right. Think about what is already done by the time a node pops: its whole left subtree is recorded, and now the node itself is too. The only thing inorder still owes it is the right subtree. Pointing curr there sends the next iteration down that subtree's left spine, and left-root-right just keeps going.

DRILL 02 · RECALL

When does the loop stop?

Both: curr null AND the stack empty. Each one means something different. A non-null curr means there is still a subtree to descend, even if the stack happens to be empty at that instant. A non-empty stack means there are ancestors still waiting to be recorded. Stop on either one alone and you exit early with half a traversal, a very common bug here.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
47 / MECHANISM UNIT 09 · ITERIN · CODE MIRRORED

A POP MEANS THE LEFT SUBTREE IS FINISHED

Inorder cannot record on the way down, because a node is not due until its whole left subtree is. So the loop runs all the way down the left spine, pushing as it goes and recording nothing, then a pop is the signal that everything to the left is complete, so the node is recorded and the walk turns right. Note the shape: an inner push-left loop wrapped in an outer pop loop. So this needs both a stack and a cursor, where preorder needed only the stack.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
48 / INTRO UNIT 10 · Iterative Postorder · 2 Stacks

UNIT 10 — Iterative Postorder · 2 Stacks

Iterative postorder with two stacks is the easy postorder. Notice this first: postorder is left → right → root, and read backwards that is root → right → left, which is just a preorder with the children swapped. So do that mirrored preorder, pushing left then right, and drop each node onto a second stack as you go. Now pop the second stack. Out comes postorder, because popping a stack reverses it. Two stacks, and no pointer bookkeeping at all.

THE QUESTION THIS LECTURE ANSWERS

HOW DO TWO STACKS TURN POSTORDER INTO AN EASY MIRRORED PREORDER?

2 stackspostorder = reverse(root-right-left)mirrored preordercollect then reverseO(n) space
WHAT TO WATCH FOR
  • 01POSTORDER REVERSED = ROOT → RIGHT → LEFT (A MIRRORED PREORDER)
  • 02STACK 1: POP, PUSH TO STACK 2, THEN PUSH LEFT THEN RIGHT ONTO STACK 1
  • 03THAT PRODUCES ROOT-RIGHT-LEFT INTO STACK 2
  • 04POP STACK 2 → THE REVERSED SEQUENCE = POSTORDER
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
49 / VIDEO UNIT 10 · Iterative Postorder · 2 Stacks

L11. Iterative Postorder Traversal using 2 Stacks

STRIVER A2Z
Iterative Postorder · 2 Stacks
RUNTIME 4:09
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
50 / DRILL UNIT 10 · Iterative Postorder · 2 Stacks

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

What is the one observation the two-stack postorder is built on?

reverse(postorder) = root-right-left. Write out left-right-root, read it backwards, and you get root-right-left, a mirrored preorder, which a single stack produces without any effort. So generate that easy order, push each node onto a second stack, and pop it. The reversal does the hard part for you. The price is O(n) extra space, and what you buy is zero pointer bookkeeping.

DRILL 02 · RECALL

You pop a node off stack 1 and push it onto stack 2.
Now its children go back onto stack 1, in what order?

Left then right. What you want flowing into stack 2 is root-right-left, so the right child must be handled before the left, so right has to end up on top of stack 1, push left first, right second. Stack 2 then reverses the whole thing into postorder. Note this is the exact opposite of iterative preorder, where you push right then left, and for the exact same reason.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
51 / MECHANISM UNIT 10 · ITERPOST2 · CODE MIRRORED

BUILD IT BACKWARDS, THEN REVERSE

Postorder is the awkward one. A node is due only after both subtrees, so a single pop can never tell you it is finished. The trick sidesteps that entirely: run a preorder with the children swapped, which emits root-right-left, and push each result onto a second stack. Draining that stack reverses the sequence into left-right-root, which is postorder. No visited-marker, no bookkeeping. The reversal does all the work, at the cost of O(n) extra space. Watch stack 2 fill in the RESULT column, then empty in exactly the right order.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
52 / INTRO UNIT 11 · Iterative Postorder · 1 Stack

UNIT 11 — Iterative Postorder · 1 Stack

Iterative postorder with one stack is the space-tight version, and the fiddly one. You walk down like inorder, but before you can record a node you have to be sure its right subtree is finished. So keep track of the last node you recorded. When you come back up to a node and its right child is either null or exactly that last node, both subtrees are done. Record it. Otherwise you still owe it the right subtree, so descend there. One stack, O(h) space, no reversal.

THE QUESTION THIS LECTURE ANSWERS

HOW DO YOU DO POSTORDER WITH A SINGLE STACK AND A 'LAST VISITED' MARKER?

1 stackprev = last recordedright done? recordelse go rightO(h) space
WHAT TO WATCH FOR
  • 01ONE STACK + A prev POINTER (THE LAST NODE RECORDED)
  • 02PEEK THE TOP; IF ITS RIGHT IS null OR == prev, BOTH SUBTREES DONE → RECORD & POP
  • 03OTHERWISE MOVE INTO THE RIGHT SUBTREE
  • 04O(h) SPACE, NO SECOND STACK, NO REVERSAL
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
53 / VIDEO UNIT 11 · Iterative Postorder · 1 Stack

L12. Iterative Postorder Traversal using 1 Stack

STRIVER A2Z
Iterative Postorder · 1 Stack
RUNTIME 12:33
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
54 / DRILL UNIT 11 · Iterative Postorder · 1 Stack

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

You are looking at the node on top of the stack.
Record it, or go right?

Right child null or already recorded ⇒ record. Otherwise go right. Postorder needs both subtrees done first. The left one is guaranteed done by the way you descended, so the only open question is the right. If the right child is null there is nothing to wait for, and if it is exactly prev then you just came back up from it. Either way the node is ready. Record it, set prev to it, pop. If neither holds, descend right. That prev check is the only thing stopping you from descending the same right subtree forever.

DRILL 02 · RECALL

Why does this version need prev at all?

Because a node's second visit looks identical to its first. A node sits on the stack the whole time both its subtrees are being processed, so when you arrive back at it, the stack alone cannot tell you whether the right subtree is still pending or already finished. prev, the node you recorded most recently. Settles it: if prev is this node's right child, you are on the way back up and the node is done. Without it you would descend right forever.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
55 / MECHANISM UNIT 11 · ITERPOST1 · CODE MIRRORED

ONE STACK, IF YOU REMEMBER WHERE YOU CAME FROM

Doing postorder in a single stack means solving the problem the two-stack version dodged: standing at a node, has its right subtree already been done, or not yet? The answer is one variable, last, the node recorded most recently. If a node's right child is last, you are coming back up from it and the node is finished; otherwise you still owe it a visit and descend right. That single comparison replaces the whole second stack, trading O(n) extra space for O(1). It is the fiddliest of the five and the one worth being able to rebuild from the idea rather than from memory.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
56 / INTRO UNIT 12 · All Three in One Pass

UNIT 12 — All Three in One Pass

All three in one pass is where the deck's claim gets proved. Push each node onto the stack carrying a count of 1, 2 or 3. On count 1: add it to preorder, bump the count to 2, go left. On count 2: add it to inorder, bump to 3, go right. On count 3: add it to postorder and pop it. Every node gets touched exactly three times, once per count, so one walk hands you all three orders together. Those three counts are the three record-points, made visible.

THE QUESTION THIS LECTURE ANSWERS

HOW DOES ONE STACK PASS PRODUCE PRE, IN AND POST TOGETHER?

(node, count) stackcount 1/2/3pre/in/post per countone passO(n) space
WHAT TO WATCH FOR
  • 01STACK OF (node, count) PAIRS; COUNT GOES 1 → 2 → 3 PER NODE
  • 02COUNT 1: ADD TO PREORDER, BUMP TO 2, GO LEFT
  • 03COUNT 2: ADD TO INORDER, BUMP TO 3, GO RIGHT
  • 04COUNT 3: ADD TO POSTORDER, POP, EACH NODE SEEN 3 TIMES
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
57 / VIDEO UNIT 12 · All Three in One Pass

L13. Preorder Inorder Postorder in One Traversal

STRIVER A2Z
All Three in One Pass
RUNTIME 10:57
AFTER THIS → 2 DRILLS · CONCEPT UNIT
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
58 / DRILL UNIT 12 · All Three in One Pass

CHECK — CAN YOU ANSWER IT WITHOUT LOOKING BACK?

DRILL 01 · RECALL

At which count does a node get added to the inorder list?

Count 2. The three counts line up exactly with the three record-points you counted in the warmup: 1 is 'before the children' (preorder), 2 is 'between them' (inorder), 3 is 'after both' (postorder). Bumping the count and leaving the frame on the stack is simulating the recursion coming back to the node after each subtree finishes.

DRILL 02 · RECALL

So what does this one pass actually tell you about the three DFS traversals?

One walk, three record-points. A single depth-first walk passes every node three times, arriving at it, coming back from the left, coming back from the right. Preorder records at the first of those moments, inorder at the second, postorder at the third. That is all they have ever been. The deck said this in unit 03; here it is running in front of you.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
59 / MECHANISM UNIT 12 · ALLTHREE · CODE MIRRORED

ONE WALK, THREE ORDERS, ONE COUNTER

The punchline of the deck. Preorder, inorder and postorder differ only in when a node is recorded relative to its two descents, so give every stack frame a visit count and let one loop do all three. Count 1 emits to preorder and descends left; 2 emits to inorder and descends right; 3 emits to postorder and pops the frame. A node is touched exactly three times, so this is still O(n), and all three lists come out together. If the deck's earlier claim. That the traversals are one recursion with the record line moved, needed proof, this is it, made literal.

THE TREE
CALL STACK
RESULT · VISIT ORDER
CODE MIRROR
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
60 / RECALL RETRIEVAL, NOT RECOGNITION

NAME THE TRAVERSAL FROM WHAT'S ASKED

DRILL 01 · TRANSFER

You need every value of a Binary Search Tree in sorted order. Which traversal, and why does it work?

Inorder. A BST's rule is left < node < right at every single node, so walking left-then-node-then-right hands you the values smallest to largest. This one fact carries a huge share of the BST section. Validate-BST, kth-smallest, BST iterator and recover-BST are all just 'do something during an inorder walk'.

DRILL 02 · RECALL

You are doing level order iteratively and you need the nodes grouped per level. How do you know where one level ends?

Read the queue size at the start of each round. Right before a level begins, the queue holds exactly that level's nodes and nothing else. So pop that many times, push children as you go, and you have isolated one level. This size-batching is what zig-zag, right-side view, level averages and nearly every 'by level' problem in deck 2 are built on.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
61 / TRAPS PLAUSIBLE, WRONG, AND SILENT

SIX WAYS TO BE PLAUSIBLY WRONG

Traversal bugs are quiet: a mirrored order from swapped calls, a missing null check, left-before-right on the stack, a level-size read too late. Each returns a believable-but-wrong sequence.

MOVING THE RECURSIVE CALLS INSTEAD OF THE RECORD LINE

For all three DFS traversals the recurse(left) and recurse(right) calls stay exactly where they are, in that order. Only the record line moves. Swap the calls and you get a mirror-image, right-to-left traversal, which quietly passes every symmetric test case and fails the rest.

FORGETTING THE null BASE CASE

if (node == nullptr) return; is the line that ends the recursion. Drop it and you dereference a null child and crash, or, in a half-written iterative version, loop forever. Every traversal opens with the null check.

ITERATIVE PREORDER: PUSHING LEFT BEFORE RIGHT

Your own stack is LIFO, so to visit left first you have to push the right child first and the left second. The left lands on top and pops next. Push left first and you get a right-to-left preorder. Nothing crashes; the answer is just wrong.

USING RECURSION DEPTH YOU DON'T HAVE

Recursive traversal costs O(h) stack frames. On a skewed tree, one shaped like a linked list. That is O(n), and for large n it overflows the call stack. When depth is the risk, move to an iterative traversal with your own stack, or Morris (deck 3, O(1) space).

LEVEL ORDER WITHOUT SNAPSHOTTING THE SIZE

If you want per-level groups, read queue.size() before the inner loop and loop exactly that many times. Read size() inside the loop and it keeps growing as you push children, so two levels merge into one. Common, and it looks perfectly reasonable.

RECORDING IN LEVEL ORDER FROM THE BACK OF THE QUEUE

Record the node you just popped from the front, never one you are pushing. Record children as you enqueue them and the left-to-right order scrambles and nodes get visited twice.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
62 / CHEATSHEET REVISION SURFACE

ONE SCREEN, THE WHOLE DECK

Nine traversals, one page. The right column is the phrase that should trigger each, the night-before surface for the whole traversal toolkit.

ALGORITHM
TIME
SPACE
REACH FOR IT WHEN
Preorder (recursive)
O(n)
O(h)
root → left → right, copy/serialize, parent before child
Inorder (recursive)
O(n)
O(h)
left → root → right. BST values come out SORTED
Postorder (recursive)
O(n)
O(h)
left → right → root, bottom-up, heights, delete, tree DP
Level order (BFS)
O(n)
O(n)
queue, front-out back-in, process by level with size-batches
Iterative preorder
O(n)
O(h)
stack; push RIGHT then LEFT so left pops first
Iterative inorder
O(n)
O(h)
push all lefts, pop+record, go right; repeat
Iterative postorder (2 stacks)
O(n)
O(n)
do root-right-left into stack 2, then reverse it
Iterative postorder (1 stack)
O(n)
O(h)
track the last node returned-from to decide direction
Pre+in+post in one pass
O(n)
O(h)
stack of (node, count 1/2/3); record at the matching count
INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
63 / CLOSE STEP 13 · DECK 1 OF 3

WALK THE TREE

A binary tree is a node with two pointers, and everything is a traversal: preorder, inorder, postorder (one recursion, three record-points) and level order (a queue). Every walk ran live on the SVG tree, numbering nodes in visit order. Deck 2 turns these four walks into depth, diameter, views, paths and LCA, the bulk of the tree interview.

00%
OF THIS DECK SOLVED
← ALL TOPICSSTEP 07 · RECURSIONSTEP 06 · LINKED LIST

Deck 1 of 3. Uses lectures L1-L13 (L3, Java representation, folded behind the code tabs). The iterative-traversal lectures are concept units, the four LC problems live on the recursive units, with iterative taught alongside. Decks 2-3 (properties, views, construction) to follow.

INVARIANT · BINARY TREES · REPRESENTATION & TRAVERSALS · DECK 1 OF 3
■ TOO SMALL TO READ
1280×720
INVARIANT · STEP 13 · DECK 1 OF 3

This one needs a laptop

Not a preference — an arithmetic one. Every slide is a fixed 1280 × 720 stage: a graph animating beside the code that drives it, with the problems laid out two columns wide. It scales as a single piece, so on a screen this size the body text comes out around 4px tall.

Shrinking it further would not help, and rebuilding it to reflow would mean losing the thing that makes it worth reading.

YOUR SCREEN0 × 0
NEEDED1060 × 610
WHAT IS WAITING ON THE LAPTOP
WATCH IT RUN, THEN RUN IT FROM MEMORY
Your progress is saved per device, so anything you tick on the laptop will be waiting there.