js 常见递归方式
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
在JavaScript中,常见的递归方式主要有两种:直接递归和间接递归。
直接递归:函数调用自身直接进行递归。
间接递归:函数调用另一个间接递归函数,最终再次调用自身进行递归。
以下是两种递归方式的示例代码:
直接递归示例 - 计算阶乘:
function factorial(n) {
if (n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 输出:120
间接递归示例 - 计算二叉树的最大宽度:
class Node {
constructor(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
}
function width(node) {
if (!node) {
return 0;
}
const leftWidth = width(node.left);
const rightWidth = width(node.right);
return Math.max(leftWidth, rightWidth) + 1;
}
const root = new Node(
'a',
new Node('b', new Node('d', null, null), new Node('e', null, null)),
new Node('c', null, new Node('f', null, null))
);
console.log(width(root)); // 输出:3
在这两个示例中,递归函数都有一个终止条件,否则会导致无限递归。递归函数通常还需要有一个从已知条件向未知条件递归的逻辑。
评论已关闭