删除节点
深度遍历(推荐层级明确时使用)
通过深度优先遍历(DFS)定位目标节点:
function removeNodeRecursive(tree, targetId) {
for (let i = 0; i < tree.length; i++) {
if (tree[i].id === targetId) {
tree.splice(i, 1); // 删除当前节点
break;
}
if (tree[i].children) {
removeNodeRecursive(tree[i].children, targetId); // 递归子节点
}
}
}
广度遍历(推荐深层次大树时使用)
用队列实现广度优先遍历(BFS),避免递归栈溢出:
function removeNodeIterative(root, targetId) {
const queue = [{ node: root, parent: null, index: 0 }];
while (queue.length) {
const { node, parent, index } = queue.shift();
if (node.data.id === targetId) {
parent.children.splice(index, 1); // 从父节点删除
break;
}
node.children.forEach((child, i) => {
queue.push({ node: child, parent: node, index: i });
});
}
}

696

被折叠的 条评论
为什么被折叠?



