Trees and Binary Trees

Lesson 14 of 20

Walk a binary tree level by level with a queue, then recurse through it inorder — with Java code that prints it.

The big picture

Meet the binary tree

Trees trade the linear world of arrays for hierarchy: one root, branches, leaves. A binary tree caps every node at two children — and traversal order suddenly matters a lot.

Count the edges

A tree with n nodes always has exactly n - 1 edges — connected and cycle-free by definition.

Binary node anatomy

Each node holds a value plus left and right references. Null links mark the boundaries: n nodes carry n + 1 of them.

Vocabulary

Root at the top, leaves at the bottom (zero children), height = longest root-to-leaf edge count. A lone node has height 0.

Four ways to walk

Preorder (node-left-right), inorder (left-node-right), postorder (left-right-node) use recursion; level order uses a queue.

Where you meet it

The DOM, file systems, expression parsing and autocomplete all live in trees — BSTs and heaps are the next step.