【发布时间】:2021-10-27 22:15:59
【问题描述】:
我有一棵树:
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: []}
【问题讨论】:
标签: javascript typescript recursion tree treeview