Typescript recursive function
Created By: chatGPT
In TypeScript, a recursive function is a function that calls itself to solve a problem. It typically breaks down the problem into smaller, more manageable parts, until it reaches a base case where it can return a result without further recursion. Here’s a simple example of a recursive function that calculates the factorial of a number:
function factorial(n: number): number {
if (n === 0) {
return 1; // base case
}
return n * factorial(n - 1); // recursive call
}
In this example, the function
factorial
takes a number n
. If n
is 0, it returns 1, which is the base case for factorial. Otherwise, it returns n
multiplied by the result of factorial(n - 1)
, effectively reducing the problem size with each call until it reaches the base case.// Testing the factorial function
const result = factorial(5);
console.log(result); // Output: 120
Another common use of recursive functions is in tree traversal. Below is an example of how to perform an in-order traversal of a binary tree recursively:
interface TreeNode {
value: number;
left?: TreeNode;
right?: TreeNode;
}
function inOrderTraversal(node: TreeNode | undefined): void {
if (!node) return; // base case
inOrderTraversal(node.left); // traverse left subtree
console.log(node.value); // visit node
inOrderTraversal(node.right); // traverse right subtree
}
In this tree traversal example, the function
inOrderTraversal
checks if the node
is undefined (base case). If it is not, it first recursively traverses the left subtree, then processes the node itself (in this case, prints its value), and finally recursively traverses the right subtree.// Example binary tree
const root: TreeNode = {
value: 1,
left: {
value: 2,
left: { value: 4 },
right: { value: 5 }
},
right: {
value: 3
}
};
// Performing in-order traversal
inOrderTraversal(root); // Output: 4, 2, 5, 1, 3