Recursion is a powerful programming technique that breaks complex problems into smaller, more manageable subproblems. It involves a function calling itself repeatedly until a base case is reached, allowing for elegant solutions to intricate computational challenges. This unit explores the anatomy of recursive functions, including base cases and recursive cases. It delves into tracing recursive calls, comparing recursion with iteration, and examining common recursive algorithms in data structures. Optimization techniques like tail recursion and memoization are also covered.
function recursiveFunction(input) { if (base case condition) { return base case result; } else { // Perform some computation // Make recursive call(s) with modified input return result combining current computation and recursive call(s); } }
function inorderTraversal(node) { if (node === null) { return; } inorderTraversal(node.left); visit(node); inorderTraversal(node.right); }
function dfs(node, visited) { visited[node] = true; visit(node); for each neighbor of node { if (!visited[neighbor]) { dfs(neighbor, visited); } } }
function mergeSort(arr, left, right) { if (left < right) { int mid = (left + right) / 2; mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); merge(arr, left, mid, right); } }
function towerOfHanoi(n, source, auxiliary, destination) { if (n === 1) { moveDisk(source, destination); return; } towerOfHanoi(n - 1, source, destination, auxiliary); moveDisk(source, destination); towerOfHanoi(n - 1, auxiliary, source, destination); }
function factorial(n, accumulator) { if (n === 0) { return accumulator; } return factorial(n - 1, n * accumulator); }
function fibonacci(n, memo) { if (memo[n] !== undefined) { return memo[n]; } if (n <= 1) { return n; } memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo); return memo[n]; }