Trees and Binary Trees

Lesson 14 of 20

Watch an inorder walk mark every node in visit order — then see why that same order prints a BST sorted.

The big picture

The big picture

A tree is the data structure of hierarchy — one root, branches, leaves. Cap every node at two children and one tiny recursive function can answer almost any question about it.

Nodes and edges

A tree stores data in nodes joined by edges. One node is the root; nodes with no children are leaves. A 7-node binary tree has exactly 6 edges.

The binary rule

Every node holds at most two children, named left and right. In C++ that is just two pointers: node->left and node->right.

Depth and height

Depth counts links from the root down to a node; height counts the longest root-to-leaf path in nodes. A lone node has depth 0 and height 1.

Three DFS orders

Inorder = left, node, right. Preorder = node, left, right. Postorder = left, right, node. Same tree, three different stories.

Recursion fits perfectly

Every subtree is itself a tree, so height(), sum() and count() are all 5-line recursive functions with one base case: the empty tree.

Where you meet them

File systems, org charts, the DOM, autocomplete tries and expression parsers are all trees doing their day jobs.