javascript - 如何找到给定ID的路径?
问题描述
我有一棵树:
type Tree = {
id: string;
pathToNode?: string[];
children: Tree[];
};
export const treeData: Tree = {
id: '1',
children: [
{
id: '2',
children: [
{ id: '3', children: [] },
{ id: '4', children: [] },
],
},
{ id: '5', children: [] },
],
};
我希望找到 id 的路径并返回该路径(或者换句话说,该节点的父节点)。
这就是我所拥有的(但它不起作用):
const findPath = (tree: Tree, id: string, pathStack: string[]) => {
if (tree.id === id) {
tree.pathToNode = pathStack;
return { id: tree.id, path: tree.pathToNode };
}
pathStack.push(tree.id);
if (tree.children.length) {
tree.children.map((node) => findPath(node, id, pathStack));
}
return { id: tree.id, path: pathStack };
};
如果我调用 findPath 并传入 id:'2',我应该得到:
const pathStack:string[] = [];
const result = findPath(treeData, '2', pathStack);
// result should equal: {id: '2', pathToNode: ['1']}
如果我调用 findPath 并传入 id:'4',我应该得到:
const pathStack:string[] = [];
const result = findPath(treeData, '4', pathStack);
// result should equal: {id: '4', pathToNode: ['1', '2']}
如果我调用 findPath 并传入 id:'5',我应该得到:
const pathStack:string[] = [];
const result = findPath(treeData, '5', pathStack);
// result should equal: {id: '5', pathToNode: ['1']}
如果我传入 '1' 的根 id,响应将是 {'1', pathToNode: []}
解决方案
您需要为孩子们早日返回并尊重返回值。
const
treeData = { id: '1', children: [{ id: '2', children: [{ id: '3', children: [] }, { id: '4', children: [] }] }, { id: '5', children: [] }] },
findPath = (tree, id, pathStack = []) => {
if (tree.id === id) return { id: tree.id, path: pathStack };
pathStack.push(tree.id);
for (const node of tree.children) {
const result = findPath(node, id, [...pathStack]);
if (result) return result;
}
};
console.log(findPath(treeData, '4'));
console.log(findPath(treeData, '5'));
推荐阅读
- angular - 确保所有依赖的 @Inputs 在子 Angular 组件中可用
- python - 在 OOP 代码中导入库的正确位置在哪里
- javascript - 使用 onclick 显示具有相同 div 类名的 2 个 div 的内容
- c++ - 是否可以更改 YOLO 对象检测(GPU 版本)中的某些代码?
- cakephp - CakePHP - 动态删除或关闭行为
- java - 春季清除会话范围bean
- wpf - 如何为 ListView WPF 控件使用“BasedOn”属性?
- excel - 我想将多个工作表设置为宏的范围
- javascript - Javascript 查找按钮的内容(每个按钮 1 个内容)
- java - 为什么我的 java 程序在我点击 server.stop(0) 后会旋转?