Sub topic 1
Trees and Their Vocabulary
A tree is a hierarchical data structure made of nodes connected by edges. Unlike a general graph, a tree has no cycle: there is exactly one path between any two nodes. A tree with one node has no edges but is still a valid tree.
Prerequisites
You should know basic programming with functions and object references, recursion, arrays, linked lists, and Big-O notation. This chapter uses the idea of a node as an object that stores a value and references to other nodes.
The Basic Terms
Consider this tree:
The terms below describe the relationships in this tree.
| Term | Meaning | Example |
|---|---|---|
| Root | The unique node with no parent | A |
| Parent | A node directly above another node | A is the parent of B |
| Child | A node directly below another node | D is a child of B |
| Leaf | A node with no children | D, E, and F |
| Edge | A direct connection between two nodes | The connection from A to B |
| Depth | Number of edges from the root to a node | depth(F) is 2 |
| Level | A position counted from the root, often depth plus 1 | F is at level 3 |
| Height of a node | Number of edges on the longest downward path to a leaf | height(B) is 1 |
| Height of a tree | Height of its root, or maximum node depth | The tree height is 2 |
| Degree of a node | Number of children of that node | degree(A) is 2 |
The root has depth 0 under the usual convention. Its children have depth 1, and their children have depth 2. A leaf has height 0 because the longest path from it to a leaf contains zero edges.
Some books define the root's level as 0 instead of 1. Always check the convention before calculating a level. Depth is usually counted in edges, while level may be counted in nodes.
The parent-child relationship is directed from parent to child. If a node is not the root, it has exactly one parent. A node may have zero, one, or many children in a general tree. The degree of the tree is the largest degree of any node.
Applying the Definitions
For the diagram:
- A is the root and has depth 0.
- B and C are children of A and have depth 1.
- D, E, and F are leaves and have depth 2.
- B has degree 2, while C has degree 1.
- A has height 2 because the longest downward path is A to B to D or E.
- The tree has 6 nodes and 5 edges.
For every nonempty tree, the number of edges is one less than the number of nodes. This follows because the root has no parent, while every other node connects to the existing tree through exactly one parent edge.
Exercise
In the displayed tree, what are the depth and height of B, and what is the degree of A?
Show answer
B has depth 1 and height 1. A has degree 2.