我有一个代表树的对象。
我要搜索节点及其搜索路径。为了搜索节点,我创建了一个运行良好的函数,下面是代码
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查找树节点。但是如何找到该物品的搜索路径?提供的功能是基于堆栈的,也可以递归回答。
答案 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
之前,需要确保该属性存在。