Esc
  • Loading…
↑ ↓ to moveEnter to openEsc to close

Binary Tree

Learn how trees branch, how to walk them in every order, and how recursion makes tree problems short — then solve the binary tree questions interviews ask most.

  • 5 Lessons
  • 16 Problems
  • 70 Illustrations

Dry-run engine

Inorder Traversal (Recursive)

Tree nodes live wherever the allocator put them; recursion follows their pointers and parks every unfinished call on the stack.

O(h) Stack Memory
Input · Traversal
left → node → right
Output · Visit order
Press play to run it
How it works

inorder(node) first recurses into node.left, then visits node, then recurses into node.right. Every call still waiting on a child is a frame on the call stack.

heap_nodes[6] + call_stack

  • node—
  • Stack depth0 frames
  • Output—

Each node is a separate heap allocation holding a value and two child addresses. Before inorder(A) can visit A, it must finish A's entire left subtree, so it recurses left first.

1 / 8

What you will learn

  • What a binary tree is: roots, children, leaves, depth, height and the LeetCode array format
  • Why trees exist, from file systems and the HTML of this page to search that takes 20 steps for a million items
  • The kinds of binary trees — full, complete, perfect, balanced, skewed — and the formulas that come with them
  • When a problem is a tree problem, and whether it wants depth-first or breadth-first search
  • How to think recursively about trees: pass information down, return answers up
  • Brute force, optimal and best solutions for 16 interview questions, each with a dry-run simulator

Why this course

Trees are where recursion stops being a trick and becomes the natural way to think: a tree is a root with two smaller trees hanging off it, so almost every tree solution is "solve it for the left subtree, solve it for the right subtree, combine".

The course starts with a deep introduction — what a binary tree is, why it exists, the types of binary trees, when to use one and how to work with one — every idea drawn, and every lesson with a simulator.

Then come the traversals every other problem builds on, the most asked interview questions, and the views of a tree. Every problem goes from brute force to optimal to the best solution, with code in four languages, a simulator that shows the tree changing step by step, and the common variations of the question.

Requirements

  • Comfort writing functions, including a function that calls itself
  • The Stack course helps: depth-first search is a stack, and breadth-first search is a queue

Course Contents