Recursive code structures
Introduction / Definition
Recursive code usually mirrors the structure of a recursive definition. It contains a base case, recursive calls on smaller structures, and a combination step. This is natural for trees and nested data. The programmer must verify termination and resource use.
Syntax / Structure / Formula
if base: return result; else: combine(recursiveCall(smaller))
Detailed Explanation
For a tree, height(empty)=0 and height(node)=1+max(height(left),height(right)).
Example
Example: A height function recursively computes both child heights.
Output / Result
The maximum child height plus one is returned.
Important Points / Notes
- Check termination.
- Deep recursion consumes call-stack space.
Mini Practice Question
What are the essential parts of recursive code?
CheckpointTest Yourself