WeCodeAcademy

Trees

A tree stores data in a hierarchy: one root node at the top, and every node can have children below it. A node with no children is a leaf. File folders, web pages (HTML) and company charts are all trees.

A binary tree allows at most two children per node, called left and right. Trees are naturally recursive: every child is itself the root of a smaller tree, so most tree code is a short recursive function. The height of a tree is the number of levels, which sets how long the longest path is.

Examplepython
Open in editor »
Quick check

What is a leaf in a tree?

Your turn: write the code

Write leaves(node) that returns how many leaf nodes the tree has. Print leaves(root).

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.