【问题标题】:How to find a path of a given id?如何找到给定ID的路径?
【发布时间】: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


    【解决方案1】:

    你的逻辑看起来不错,只需要更正一些 我在你需要修正的代码中添加了一些 cmets

    const findPath = (tree: Tree, id: string, pathStack: string[]) => {
      if (tree.id === id) {
        tree.pathToNode = pathStack;  // no need to add pathstack to tree
        return { id: tree.id, path: tree.pathToNode };  // use pathStack instead of tree.pathToNode
      }
      pathStack.push(tree.id);
    
      if (tree.children.length) {
        tree.children.map((node) => findPath(node, id, pathStack)); // this will loops to all your childs even if you find the result node 
    //So use for loop and break the loop when you find the result node 
    
    
      }
    
      return { id: tree.id, path: pathStack };
    };
    

    我的代码是

    const findPath = (tree: Tree, id: string, pathStack: string[]) => {
        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; //this will stop going deeper or to unwanted childs after getting the result
        }
    };
    

    正如评论中讨论的那样,在数组中查找某些节点的路径。

    let foundPaths = [];
    let path
    arr.map(element => {
     path = findPath(tree, element.id);
     if(path) {foundPaths.push(path)}
    })
    

    【讨论】:

    • 嗨 sojin,我正在使用 typeScript,该解决方案有效,但它缺少结束返回语句,有什么想法吗?我不想返回 undefined。
    • 当我们找到正确的节点时,我们正在返回结果。如果没有找到结果,你需要返回 undefined 或 null,我认为
    • 我实际上是通过这样的列表映射这个函数:const foundPaths = arr.map((element) => findPath(tree, element.id) );我将在数组中得到值和未定义。有没有办法在我的数组中没有任何未定义的?我想不出解决办法。
    • 明白,我已经在答案中添加了解决方案。请检查。
    • 我明白了,所以您不会在 .map 中返回任何内容,而是将值推送到数组中。这样可行。 :) 谢谢你的帮助
    【解决方案2】:

    为孩子早点回来,尊重返回值。

    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'));

    【讨论】:

    • 嗨 Nina,我正在使用 typeScript,该解决方案有效,但它缺少结束返回语句,有什么想法吗?我不想返回 undefined。
    • @webber:如果找不到东西,你想返回什么?返回 undefined 是 JS 对尝试查找缺失值的惯用响应。你可能不想扔。那么在这种情况下你想返回什么?
    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多