Sub topic 1
Trees and their vocabulary
Prerequisites
This chapter assumes you can do the following:
- Write and read simple functions, including recursive ones.
- Understand object references or pointers (a variable that refers to another object).
- Read Big-O notation such as O(n) and O(log n).
- Know how arrays and linked lists store data.
No tree knowledge is needed. This chapter only builds the vocabulary. Later chapters use it for binary trees, traversals and binary search trees. GATE questions often hide a simple counting task inside precise wording, so each term here is defined exactly.
What a tree is
A tree is a data structure made of nodes connected by edges. It represents a hierarchy. Examples are a file system, an organisation chart and the nested structure of an expression.
A tree can be defined in two equivalent ways.
Graph definition. A tree is a connected graph with no cycles. If it has n nodes, it has exactly n - 1 edges.
Recursive definition. A tree is either empty, or it is a single node called the root together with zero or more disjoint trees, called the subtrees of the root. Each subtree's root is joined to the root by one edge.
The recursive definition is the one you will use most. Almost every tree algorithm in this tutorial follows it. It handles the empty tree, then the root, then each subtree.
The edge count of n - 1 follows from the recursive definition. Every node except the root has exactly one edge going up to its parent. That gives n - 1 edges.
Core vocabulary
Consider this tree.
The terms below are all illustrated with this tree.
| Term | Definition | Example in the tree |
|---|---|---|
| Root | The one node with no parent | A |
| Parent | The node directly above a node | B is the parent of E |
| Child | A node directly below a node | E and F are children of B |
| Siblings | Nodes with the same parent | E and F; also B, C and D |
| Leaf (external node) | A node with no children | C, E, G, H, I |
| Internal node | A node with at least one child | A, B, D, F |
| Ancestor | Any node on the path from the root to this node, excluding itself | Ancestors of H are F, B, A |
| Descendant | Any node in the subtree below this node, excluding itself | Descendants of B are E, F, H, I |
| Degree of a node | The number of children of that node | Degree of A is 3; of C is 0 |
| Degree of a tree | The largest node degree in the tree | 3 |
| Edge | A link between a parent and a child | A to B |
| Path | A sequence of nodes where each consecutive pair is joined by an edge | A, B, F, H |
| Subtree | A node together with all its descendants | The subtree at F contains F, H, I |
Two points cause frequent mistakes.
- Degree in a rooted tree counts only children. In general graph theory degree counts all incident edges, so a non-root node would have one more. In tree questions, "degree of a node" means the number of children.
- Some books count a node as its own ancestor and descendant. GATE questions normally say "proper" when they mean to exclude the node itself. Read the wording carefully.
Depth, height and level
These three terms measure position and size. They are the ones most often confused.
- Depth of a node is the number of edges on the path from the root to that node. The root has depth 0.
- Height of a node is the number of edges on the longest downward path from that node to a leaf. A leaf has height 0.
- Height of a tree is the height of its root. It equals the largest depth of any node.
- Level of a node is usually its depth. Many sources start at level 0 for the root, and others start at level 1.
For the sample tree:
| Node | Depth | Height |
|---|---|---|
| A | 0 | 3 |
| B | 1 | 2 |
| C | 1 | 0 |
| D | 1 | 1 |
| F | 2 | 1 |
| H | 3 | 0 |
The tree has height 3, because the longest root-to-leaf path is A, B, F, H, which has 3 edges.
Depth looks up from a node to the root. Height looks down from a node to its deepest leaf. A useful check: the depth of the root is always 0, and the height of every leaf is always 0.
Computing height recursively
Height follows the recursive definition. The height of a node is one more than the largest height among its children. A leaf has no children, so its height is 0. An empty tree has height -1 under the edge convention. That choice makes the formula work with no special case for leaves.
The code below uses a general tree, where each node holds a list of children.
class TreeNode:
def __init__(self, label, children=None):
self.label = label
self.children = children or []
def height(node):
if node is None:
return -1
if not node.children:
return 0
return 1 + max(height(child) for child in node.children)
def degree_of_tree(node):
if node is None:
return 0
own = len(node.children)
return max([own] + [degree_of_tree(c) for c in node.children])
def count_nodes(node):
if node is None:
return 0
return 1 + sum(count_nodes(c) for c in node.children)
h = TreeNode("H")
i = TreeNode("I")
f = TreeNode("F", [h, i])
e = TreeNode("E")
b = TreeNode("B", [e, f])
c = TreeNode("C")
g = TreeNode("G")
d = TreeNode("D", [g])
a = TreeNode("A", [b, c, d])
print(height(a)) # 3
print(degree_of_tree(a)) # 3
print(count_nodes(a)) # 9Running this prints 3, 3 and 9. These match the table and the diagram. The function count_nodes also confirms the edge formula: 9 nodes and 8 edges.
Facts that follow from the definitions
Several results are used constantly in later chapters.
- A tree with n nodes has n - 1 edges.
- There is exactly one path between any two nodes. If there were two, they would form a cycle.
- Adding any edge between two existing nodes creates a cycle. Removing any edge disconnects the tree.
- The sum of the degrees (child counts) of all nodes equals n - 1, because each edge is counted once at its parent.
- For a tree where every internal node has exactly m children (an m-ary tree with this property), the numbers of internal nodes i and leaves L satisfy L = (m - 1)i + 1.
Fact 5 is worth deriving once, because it appears in many GATE questions. The total number of nodes is n = i + L. The total number of edges is n - 1 = m·i, because every internal node has m children. Substituting n = i + L gives i + L - 1 = m·i. So L = (m - 1)i + 1.
Worked example: a tree in which every internal node has 3 children has 10 internal nodes. Then L = (3 - 1) × 10 + 1 = 21 leaves, and the total number of nodes is 31.
Common errors
- Mixing depth and height. Depth is measured from the root down to the node. Height is measured from the node down to its deepest leaf. A leaf can have a large depth but its height is always 0.
- Counting nodes instead of edges. A path with 4 nodes has length 3. If an answer is off by one, check this first.
- Using the wrong degree. Tree degree counts children only. A node with a parent and two children has degree 2, not 3.
- Treating "leaf" as "any node that is not the root". A leaf is a node with no children. A root with no children is both the root and a leaf, in a single-node tree.
- Forgetting that levels may start at 1. Check whether the question numbers the root as level 0 or level 1 before using a formula such as "level k has at most 2^k nodes".
- Assuming a tree must be binary. The vocabulary here applies to any number of children. Restricting to two children is the next chapter's topic.
Summary of how the terms relate
Along any root-to-leaf path in which the leaf is at the deepest level, depth increases by 1 at each step down and height decreases by 1. On such a path, depth plus height equals the tree height. This holds only for nodes on a longest path. For a node on a shorter branch, depth plus height is smaller than the tree height.
Exercise
A tree has 40 nodes. Every internal node has exactly 3 children. How many leaves and how many internal nodes does it have? How many edges does it have?
Show answer
Let i be the number of internal nodes and L the number of leaves. Then i + L = 40, and L = (3 - 1)i + 1 = 2i + 1. Substituting gives i + 2i + 1 = 40, so 3i = 39 and i = 13. Then L = 27. The number of edges is n - 1 = 39. Check: 13 internal nodes with 3 children each give 39 edges.
Exercise
In the sample tree from this chapter, state the depth and height of node F, the degree of node A, the ancestors of node I, and the leaves of the tree.
Show answer
Node F has depth 2 (path A, B, F has 2 edges) and height 1 (the longest downward path F to H has 1 edge). Node A has degree 3 because it has children B, C and D. The ancestors of I are F, B and A. The leaves are C, E, G, H and I.
Exercise
A tree has height 0 under the edge-counting convention. What does the tree look like? What is its height under the node-counting convention, and what are the height of the empty tree under each convention?
Show answer
A tree with height 0 under the edge-counting convention consists of a single node, the root, with no edges. Under the node-counting convention the same tree has height 1. The empty tree has height -1 under the edge convention and height 0 under the node convention.