发布于 5年前

js数组如何利用递归遍历树并转换为二维数组

问题描述

js数组如何利用利用递归遍历树并转换为二维数组?

有一棵树,例如:

let arr = [
    {
        name: '1',
        children: [
            {
                name: '1-1',
                children: [
                    {
                        name: '1-1-1',
                        children: []
                    },
                ]
            }, {
                name: '1-2',
                children: [
                    {
                        name: '1-2-1',
                        children: [
                            {
                                name: '1-2-1-1',
                                children: []
                            },
                        ]
                    },
                    {
                        name: '1-2-2',
                        children: []
                    },
                ]
            }, {
                name: '1-3',
                children: [
                    {
                        name: '1-3-1',
                        children: []
                    },
                ]
            },
        ]
    },
    {
        name: '2',
        children: [
            {
                name: '2-1',
                children: [
                    {
                        name: '2-1-1',
                        children: []
                    },
                    {
                        name: '2-1-2',
                        children: []
                    },
                ]
            },
            {
                name: '2-2',
                children: []
            },
        ]
    },
    {
        name: '3',
        children: [
            {
                name: '3-1',
                children: []
            },
        ]
    },
];

如何利用递归活其他方法把它转换为二维数组?期待的结果如下:

let result = [
    ["1", "1-1", "1-1-1"],
    ["1", "1-2", "1-2-1", "1-2-1-1"],
    ["1", "1-2", "1-2-2"],
    ["1", "1-3", "1-3-1"],
    ["2", "2-1", "2-1-1"],
    ["2", "2-1", "2-1-2"],
    ["2", "2-2"],
    ["3", "3-1"],
];

解决方案

其实就是遍历把每个叶子节点的路径保存下来而已,建议了解一下深度优先遍历。

给一下写法吧:

function generatePath(tree, stack = [], pathList = []) {
  if (!tree) return
  for (let data of tree) {
    stack.push(data.name)
    if (data.children && data.children.length) {
      generatePath(data.children, stack, pathList)
    } else {
      pathList.push([...stack])
    }
    stack.pop(data.name)
  }
  return pathList
}

let list = generatePath(arr)
console.log(JSON.stringify(list))

输出:

[
    [
        "1",
        "1-1",
        "1-1-1"
    ],
    [
        "1",
        "1-2",
        "1-2-1",
        "1-2-1-1"
    ],
    [
        "1",
        "1-2",
        "1-2-2"
    ],
    [
        "1",
        "1-3",
        "1-3-1"
    ],
    [
        "2",
        "2-1",
        "2-1-1"
    ],
    [
        "2",
        "2-1",
        "2-1-2"
    ],
    [
        "2",
        "2-2"
    ],
    [
        "3",
        "3-1"
    ]
]
©2020 edoou.com   京ICP备16001874号-3