Trees and Binary Trees

Lesson 14 of 20

One binary tree, three walks — recursive inorder, a stack-driven preorder and a queue-powered level sweep.

The big picture

Meet the trees

A tree is a list that grew branches: one root on top, exactly one path down to every node, and a whole new set of ways to visit the data.

Hierarchy, not a line

Lists and stacks are linear. Trees branch — one root, and every other node has exactly one parent above it.

Binary = at most two

Each node keeps up to two children, named left and right. That single rule is all a binary tree needs.

Three DFS orders

Depth-first walks come in three flavours: inorder (left, node, right), preorder (node, left, right), postorder (left, right, node).

BFS rides a queue

Level-order visits top to bottom, left to right — a deque holds the waiting line of nodes.

Height and depth

Depth counts edges from the root down to a node; height is the longest root-to-leaf path. Our 7-node tree is 2 edges tall.

Leaves and None

A leaf has zero children. In Python, missing children are None — the base case every tree recursion stops at.