面试题答案
一键面试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);
优化递归实现以避免栈溢出问题
- 使用尾递归优化:在某些支持尾递归优化的编程语言(如 Scala、Scheme 等)中,可以将递归函数改写成尾递归形式,编译器会自动优化,避免栈溢出。但 JavaScript 目前没有原生支持尾递归优化。
- 手动模拟栈:使用一个栈数据结构来模拟递归调用的过程,将递归实现转换为迭代实现。
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);
上述代码通过手动模拟栈的方式,将递归的深度优先遍历转换为迭代形式,避免了递归调用带来的栈溢出风险。