MST

星途 面试题库

面试题:JavaScript递归函数优化树形结构遍历

假设有一个树形结构数据,每个节点有一个 `children` 数组来表示子节点。请使用递归函数实现深度优先遍历该树形结构,并在遍历过程中为每个节点添加一个 `depth` 属性表示其深度。同时,思考如何优化递归实现以避免栈溢出问题。例如树形结构数据如下:`{ value: 'root', children: [ { value: 'child1', children: [ { value: 'grandchild1', children: [] } ] }, { value: 'child2', children: [] } ] }`。
18.1万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function dfsTraversal(node, depth = 0) {
    if (!node) return;
    node.depth = depth;
    if (node.children && node.children.length > 0) {
        for (let child of node.children) {
            dfsTraversal(child, depth + 1);
        }
    }
}

// 示例用法
const tree = { 
    value: 'root', 
    children: [ 
        { value: 'child1', children: [ { value: 'grandchild1', children: [] } ] }, 
        { value: 'child2', children: [] } 
    ] 
};
dfsTraversal(tree);
console.log(tree);

优化递归实现以避免栈溢出问题

  1. 使用尾递归优化:在某些支持尾递归优化的编程语言(如 Scala、Scheme 等)中,可以将递归函数改写成尾递归形式,编译器会自动优化,避免栈溢出。但 JavaScript 目前没有原生支持尾递归优化。
  2. 手动模拟栈:使用一个栈数据结构来模拟递归调用的过程,将递归实现转换为迭代实现。
function iterativeDFS(node) {
    const stack = [[node, 0]];
    while (stack.length > 0) {
        const [currentNode, currentDepth] = stack.pop();
        if (currentNode) {
            currentNode.depth = currentDepth;
            if (currentNode.children && currentNode.children.length > 0) {
                for (let i = currentNode.children.length - 1; i >= 0; i--) {
                    stack.push([currentNode.children[i], currentDepth + 1]);
                }
            }
        }
    }
}

// 示例用法
const tree2 = { 
    value: 'root', 
    children: [ 
        { value: 'child1', children: [ { value: 'grandchild1', children: [] } ] }, 
        { value: 'child2', children: [] } 
    ] 
};
iterativeDFS(tree2);
console.log(tree2);

上述代码通过手动模拟栈的方式,将递归的深度优先遍历转换为迭代形式,避免了递归调用带来的栈溢出风险。