Question
What is a tree in computer science, and what kind of data is it used for?
Answer
A tree represents a hierarchy: it consists of nodes in parent-child relationships, with one node at the top and every other node having exactly one parent. It is used wherever data is naturally nested, such as file systems, organisation charts and program structure.
The linear structures (lists, stacks, queues) arrange data in a line: every element has at most one predecessor and one successor. A tree relaxes the second half of that. A node still has exactly one parent (except the top node, which has none), but it may have any number of children. That is precisely the shape of a hierarchy.
Examples of hierarchical data a tree models directly:
- File systems: a drive contains folders, folders contain folders and files.
- Organisation charts: a department has teams, teams have members.
- Product breakdowns: a vehicle has a drive train, a chassis and accessories, each with its own parts.
- Programming environments: a program's source is parsed into a syntax tree; classes contain methods, methods contain statements.
The single-parent rule is what makes it a tree rather than a general graph: from the top node there is exactly one path down to every node, so there are no cycles and no node can be reached two ways.
Go deeper:
Tree (abstract data type) — the terminology, the common operations and the ways of representing a tree.
Note saved — thanks!
Question
What are the root, an internal node and an external node (leaf) of a tree?
Answer
The root is the only node without a parent; an internal node has at least one child; an external node, or leaf, has no children.
* A is the root; B, C and F are internal; E, I, J, K, G, H and D are leaves; C with G and H forms a subtree. *
Every node of a tree falls into exactly one of these categories by counting its parent and its children:
| Term | Condition | In the example |
|---|---|---|
| Root | no parent | A |
| Internal node | at least one child | A, B, C, F |
| External node / leaf | no children | E, I, J, K, G, H, D |
The root is usually also internal. It counts as a leaf only in the degenerate tree with a single node.
The internal/external split matters for algorithms. Many recursive tree algorithms have their base case at the leaves (nothing below, so the answer is immediate) and their recursive case at internal nodes (combine the answers of the children). Height and expression evaluation both follow this pattern.
Note saved — thanks!