Skip to content

[js] 第493天 写一个方法,实现树的路径查询[代码] #2805

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第493天 写一个方法,实现树的路径查询[代码]

作者:ustchcl

3+1官网

我也要出题

给定以下树结构

type Tree = {
  id: number;
  name: string;
  children: Tree[];
}

const tree: Tree = {
  id: 1,
  name: "中国",
  children: [
    {id: 2, name: "北京市", children: [
      {id: 3, name: "朝阳区", children: []},
      {id: 4, name: "海淀区", children: []},
    ]},
    {id: 5, name: "上海市", children: [
      {id: 6, name: "徐汇区", children: []},
      {id: 7, name: "黄浦区", children: []},
    ]},
  ]
}

function findPathById(id: number): string {
  // 在这儿书写
}

findPathById(4) // 中国北京市海淀区

Activity

TheSunRisesAsUsual

TheSunRisesAsUsual commented on Aug 21, 2020

@TheSunRisesAsUsual
 function findPathById(id, Tree) {
    let res = []
    function get(tree, arr = []) {
      Array.isArray(tree) && tree.forEach(val => {
        let arrX = JSON.parse(JSON.stringify(arr)) //拷贝一下数组
        arrX.push(val.name)
        val.id === id ? (res = arrX) : val.children && get(val.children, arrX)
      })
    }
    get([Tree])
    return res.join(",")
  }
  const str = findPathById(4, Tree)
wheatup

wheatup commented on Aug 21, 2020

@wheatup
const tree = {
    id: 1,
    name: "中国",
    children: [
        {
            id: 2, name: "北京市", children: [
                { id: 3, name: "朝阳区", children: [] },
                { id: 4, name: "海淀区", children: [] },
            ]
        },
        {
            id: 5, name: "上海市", children: [
                { id: 6, name: "徐汇区", children: [] },
                { id: 7, name: "黄浦区", children: [] },
            ]
        },
    ]
}

function findPathById(id) {
    const path = [];
    
    const find = (node, depth, id) => {
        path[depth] = node;
        if(node.id === id) {
            return node;
        }

        for(let n of node.children) {
            const result = find(n, depth + 1, id);
            if(result) {
                path[depth + 1] = n;
                return result;
            }
        }
    }
    find(tree, 0, id);
    return path.reduce((acc, e) => acc + e.name, '');
}

console.log(findPathById(4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@wheatup@TheSunRisesAsUsual

        Issue actions

          [js] 第493天 写一个方法,实现树的路径查询[代码] · Issue #2805 · haizlin/fe-interview