繁体   English   中英

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

[英]How to find search path of node in tree js/ts

我有一个代表一棵树的对象。

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

 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查找树节点。 但是如何找到该物品的搜索路径? 提供的功能是基于堆栈的,以递归回答也是可以的。

您可以将节点和当前路径同时压入堆栈,然后进行相应处理。 我假设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 stack.pop() || null; 只能return null ,因为stack为空。 如果undefined可以作为返回值,则可以省略整行。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM