Recursive data types
Introduction / Definition
A recursive data type refers to itself in its definition. It naturally models lists, trees, and nested structures. A recursive definition normally contains a base case and a recursive case. Algorithms can then mirror this structure.
Syntax / Structure / Formula
List<T> = Empty | Node(T, List<T>)
Detailed Explanation
A list is either empty or a node containing a value and another list. Binary trees can similarly contain child trees.
Example
Example: Node(10, Node(20, Empty)).
Output / Result
The structure contains two values and terminates at Empty.
Important Points / Notes
- Always define a base/empty case.
- Lists and trees are common examples.
Mini Practice Question
Give a recursive definition of a binary tree.
CheckpointTest Yourself