如何在树js / ts中查找节点的搜索路径

时间:2019-07-09 10:32:17

标签: javascript typescript tree

我有一个代表树的对象。

我要搜索节点及其搜索路径。为了搜索节点,我创建了一个运行良好的函数,下面是代码

let treeData = {
  id: 1,
  name: "Node 1",
  child: [{
      id: 2,
      name: "Node 2",
      child: [{
          id: 3,
          name: "Node 3"
        },
        {
          id: 4,
          name: "Node 4",
          child: [{
            id: 10,
            name: "Node 10"
          }]
        }
      ]
    },
    {
      id: 5,
      name: "Node 5",
      child: [{
        id: 6,
        name: "Node 6"
      }]
    }
  ]
};


function _searchTree(nodeId, parent) {
  const stack = [parent];
  while (stack.length) {
    const node = stack.pop();
    if (node.id === nodeId) {
      return node;
    }
    if (node.child) {
      stack.push(...node.child);
    }

  }
  return stack.pop() || null;
}
const _node = _searchTree(10, treeData);

console.log("Found node", _node);

此函数可以根据传递的ID查找树节点。但是如何找到该物品的搜索路径?提供的功能是基于堆栈的,也可以递归回答。

1 个答案:

答案 0 :(得分:1)

您可以将节点和当前路径同时压入堆栈,然后进行相应处理。我假设path元素是child数组中的索引。

这是它的外观:

function _searchTree(nodeId, parent) {
    const stack = [[parent, []]];
    while (stack.length) {
       const [node, path] = stack.pop();
       if (node.id === nodeId) {
          return path;
       }
       if (node.child) {
           stack.push(...node.child.map((node, i) => [node, [...path, i]]));
       }
    }
}

const a = {id: 1,name: "Node 1",child: [{id: 2,name: "Node 2",child: [{id: 3,name: "Node 3"},{id: 4,name: "Node 4",child: [{ id: 10, name: "Node 10" }]}]},{id: 5,name: "Node 5",child: [{id: 6,name: "Node 6"}]}]};
const path = _searchTree(6, a);
console.log(path); // [1, 0]

请注意,您的原始代码也有两个更正:

  • 最后一个return stack.pop() || null;可以是return null,因为此时stack为空。如果undefined可以作为返回值,则可以省略整行。

  • 在迭代node.child之前,需要确保该属性存在。