递归遍历树结构时如何避免栈溢出?

培静 ☘︎ 阅读 19

我在处理一个后台返回的部门树形数据,用递归去查找某个节点,但数据量大时浏览器直接报栈溢出错误。试过把递归改成尾递归,但好像JS引擎也不优化,还是崩。

有没有更稳妥的办法?比如转成循环?下面是我现在的写法:

function findNode(tree, id) {
  if (!tree || tree.length === 0) return null;
  for (let node of tree) {
    if (node.id === id) return node;
    const found = findNode(node.children, id);
    if (found) return found;
  }
  return null;
}
我来解答 赞 7 收藏
二维码
手机扫码查看
2 条解答
 ___嘉煊
把递归改成迭代用栈模拟搞定

function findNode(tree, id) {
const stack = tree ? [...tree] : [];
while (stack.length > 0) {
const node = stack.pop();
if (node.id === id) return node;
if (node.children) stack.push(...node.children);
}
return null;
}
点赞
2026-03-30 12:11
长孙风珍
我之前也遇到过这问题,直接改成循环就完事。把递归变成显式的栈操作,用数组模拟调用栈就行。代码给你:

function findNode(tree, id) {
let stack = tree ? [tree] : [];
while (stack.length > 0) {
let nodes = stack.pop();
for (let node of nodes) {
if (node.id === id) return node;
if (node.children && node.children.length) stack.push(node.children);
}
}
return null;
}


这个写法稳得一批,不用怕爆栈了。
点赞
2026-03-29 13:40