Unit 4 of 8 · about 4 hours · implement

Tree representation and traversals

Every tree algorithm is a traversal with extra state. The traversal order decides which questions a single pass can answer.

You'll be able to

  • Represent binary trees with node objects and array layouts, and convert between them.
  • Implement recursive and iterative preorder, inorder, postorder and level-order traversals with differential tests.
  • Diagnose recursion-depth, null-marker and queue-shape defects on skewed, empty and single-node trees.

Covers

Tree nodes, parent state, recursion and iterative stacksPreorder, inorder, postorder and level-order traversal
1

Read

In this order, only the parts listed

0 of 3 done

  1. Binary tree fundamentalsDSA Handbook - search, trees and heaps

    What a binary tree is; Three shape restrictions worth naming; Two ways to store a tree in memory; The post-order recursion template; Recursion depth on skewed inputs

  2. Tree traversals: pre, in, postDSA Handbook - search, trees and heaps

    The five-line skeleton; The canonical tree; Iterative inorder via explicit stack; Iterative pre and post via explicit stack; Building a tree from two of its traversals; Pitfalls that bite

    Skim the LC 297 worked example for the null-marker rule only; the full codec is not implemented here.

  3. Level-order traversal: BFS on treesDSA Handbook - search, trees and heaps

    The trigger; The pattern; What changes between the variants; Two pitfalls that bite

2

Focus on

  • Height convention used here: height(null) = 0 and a leaf has height 1 (nodes on the path). The AVL chapter switches to edges; never mix the two conventions in one argument.
  • Iterative inorder keeps every ancestor whose left subtree is done but whose value is unemitted; after emitting, move to cur.right, not None.
  • Level order needs the level_size = len(queue) snapshot taken once per level. Reading the queue length inside the inner loop merges levels.
  • CPython's default recursion limit is 1000 (check with sys.getrecursionlimit), so a recursive traversal fails on a skewed tree of a few thousand nodes while a balanced tree of 100,000 nodes (depth about 17) is fine. The iterative forms have no such cap.
Common mistakes · 3
  • Pushing the left child before the right in iterative preorder. Push right first so the left child pops next.
  • Serializing without null markers. Preorder [2,1] fits two different trees; markers disambiguate.
  • Using list.pop(0) as the BFS queue. Each pop costs , which makes level order ; use collections.deque.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement iterative inorder and level-order with the snapshot line. On the chapter's canonical tree (preorder [1,2,4,5,3,6], inorder [4,2,5,1,3,6]), return inorder [4,2,5,1,3,6] and level order [[1],[2,3],[4,5,6]]. Check both against recursive versions on 200 random BSTs up to 25 nodes with fixed seeds, plus empty, single-node and skewed inputs.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does inorder traversal of a BST emit sorted keys?Answer

    Inorder visits the left subtree, then the node, then the right subtree. Every key left of a node is smaller and every key right of it is larger, so induction on the tree gives ascending order. This needs the BST invariant and is false for general binary trees.

  2. 2.What breaks if the inner level-order loop reads len(queue) on every check instead of snapshotting?Answer

    Children appended during the level change the bound mid-level, so the loop consumes the next level too and the boundaries merge. The snapshot fixes the count before any appends happen.

  3. 3.Preorder [1,2] and postorder [2,1] fit more than one tree. Show the ambiguity and the fix.Answer

    Both fit root 1 with a single child 2 on either side; the one-child direction is undetermined. Null markers (or an inorder sequence, which needs distinct keys) fix the shape.

  4. 4.A recursive inorder fails on a skewed tree of 5,000 nodes but works on a balanced tree of 100,000. Why?Answer

    Stack use follows depth, not size: skewed depth is against the default limit of 1000, while balanced depth is about 17. The fix is the iterative form, or a deliberate limit raise.

5

Practice

  • LeetCode 94: Binary Tree Inorder Traversal

    Solve recursively, then iteratively with an explicit stack; the follow-up asks for the iterative form

    After submitting, read the AlgoMaster write-up for Binary Tree Inorder Traversal (https://algomaster.io/learn/dsa/binary-tree-inorder-traversal).

  • LeetCode 102: Binary Tree Level Order Traversal

    Group output by level with the snapshot line; example tree [3,9,20,null,null,15,7] expects [[3],[9,20],[15,7]]

    After submitting, read the AlgoMaster write-up for Binary Tree Level Order Traversal (https://algomaster.io/learn/dsa/binary-tree-level-order-traversal).

You're done when

Both iterative traversals match their recursive twins on 200 random trees, you reproduce the canonical orders from memory, and empty, single-node and skewed inputs all pass.

Only when you can do this without notes.

Leads to

Notes

Resources · 1 for this unit, 9 more in the section
  • DSA Handbook - search, trees and heapsHandbook Academy · primary

    Study Part 2 Search and Sort, Part 5 Linked Lists, and Part 6 Trees and Heaps. Include canonical and answer-space binary search, comparison and linear-time sorts, quickselect, sentinels, cycles, heaps, BSTs, balanced-tree vocabulary, tries and segment trees.

Also in this section

  • AlgoMaster DSA - ordered structures sliceAlgoMaster · required

    Attempt Koko Eating Bananas, Validate Binary Search Tree and Find Median from Data Stream cold. Use Merge Intervals only if interval modeling remains weak, and include duplicate-heavy and skewed inputs.

  • Algorithmica - search and sorting performanceSergey Slotin · support

    Use the binary-search, sorting, branch prediction and cache chapters to explain why two algorithms with the same asymptotic bound cross over on real workloads.

  • AlgorithmsJeff Erickson · reference

    Use Chapter 1 (mergesort, quicksort, recursion trees and linear-time selection) when deriving merge, partition and selection algorithms, and lecture note 12 Lower Bounds for the comparison-sorting decision-tree argument. This is the proof reference when the handbook explanation is too brief.

  • NeetCode - unseen ordered problemsNeetCode · optional

    Use one unseen tree problem and one heap or interval problem as the final transfer check, with solution material closed until submission.

  • DSA Handbook Patterns - quicksort vs mergesort vs heapsortHandbook Academy · support

    Use The decision, Algorithms compared and Side-by-side to pick a comparison sort from the binding constraint; problem details stay with their units.

  • DSA Handbook Patterns - quickselect vs heap for top-KHandbook Academy · support

    Use The decision through Side-by-side for the streaming, sorted-output and mutation routing; problem details stay with their units.

  • DSA Handbook Patterns - two-heap median archetypesHandbook Academy · support

    Use Streaming median and Variants side-by-side for the two-heap invariants; skip sliding-window median and sketches.

  • DSA Handbook Patterns - merge intervals archetypesHandbook Academy · support

    Use The decision, Variants and the LC 56 and LC 57 signature problems for merge and insert implementation, and the Meeting Rooms II archetype for the min-heap form.

  • DSA Handbook Patterns - sweep line archetypesHandbook Academy · support

    Use The decision and the 1D event sweep variant for +1/-1 concurrency counting with explicit tie-breaks; skyline and rectangle area are recognition only.