What is a tree in computer science, and what kind of data is it used for?
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.