JavaScript 树结构操作

删除节点

深度遍历(推荐层级明确时使用)

通过深度优先遍历(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 });
    });
  }
}

参考:https://mp.weixin.qq.com/s?__biz=MzI5MzQ1Mjg3OQ==&mid=2247483946&idx=1&sn=da5212f9b04f4c54530483947ca69527&poc_token=HJ-qdWijl3x-9XVCwtwT5IkADB7K6NbA0vI6rAES

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值