Understand rooted trees, parent–child relationships, leaves, depth and traversal, and recognise tree structures in file systems and search indexes.
01
Learning objectives
Identify nodes, edges, roots, leaves, parents and children.
Explain the difference between a general tree and a binary tree.
Trace preorder, inorder and postorder traversal on a small tree.
Describe how hierarchical structures support search and organisation.
02
Lesson notes
A tree is a hierarchical structure made of nodes connected by edges. A rooted tree has one designated root; each other node has one parent and may have zero or more children. A node without children is a leaf. The number of edges on the path from the root to a node is its depth; the longest downward path helps define tree height.
A binary tree restricts each node to at most two children, commonly called left and right. A binary search tree adds an ordering rule: values in the left subtree are smaller than the node and values in the right subtree are larger, subject to the chosen duplicate policy. This can make search efficient when the tree remains balanced, but a badly skewed tree can behave like a linked list.
Traversal is a systematic way to visit nodes. Preorder visits root, left, right; inorder visits left, root, right; postorder visits left, right, root. In a binary search tree, inorder traversal visits keys in sorted order. Traversal is useful for displaying, searching, copying or deleting hierarchical data.
Trees naturally represent folders, organisational charts, XML/HTML documents, decision processes and indexes. The structure makes relationships explicit. The shape matters for efficiency: a balanced tree has height roughly proportional to log n, while a chain of n nodes has height n.
03
Worked code examples
Worked example
The recursive inorder traversal visits the left subtree, then the node, then the right subtree.