递归遍历树结构时如何避免栈溢出?
我在处理一个后台返回的部门树形数据,用递归去查找某个节点,但数据量大时浏览器直接报栈溢出错误。试过把递归改成尾递归,但好像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;
}
这个写法稳得一批,不用怕爆栈了。