递归树算法如何实现到嵌套递归数组

时间:2019-05-02 18:31:43

标签: javascript arrays algorithm recursion data-structures

有一个受哈希树对象启发的数组。但是结构设计不好,有点复杂。

const directories = [
  "/main",
  [
    "folder",
    ["subFolder", ["directory1", "directory2", "directory3"]],
    "folder2",
    ["subFolder", ["directory4", "directory5"]],
    "folder3",
    [
      "subFolder",
      ["directory4", "directory5", "directory6", "directory7"],
      "subFolderWrapper",
      ["folder1", ["subFolder", ["child1", "child2", "child3", "child4"]]]
    ]
  ]
]

必须创建一个递归函数,并根据给定的嵌套关系返回一个新数组。

像这样的东西
const result = [
  "/main/",
  [
    "/main/folder",
    [
      "/main/folder/subFolder",
      [
        "/main/folder/subFolder/directory1",
        "/main/folder/subFolder/directory2",
        "/main/folder/subFolder/directory3"
      ]
    ],
    "/main/folder2",
    [
      "/main/folder2/subFolder",
      [
        "/main/folder2/subFolder/directory4",
        "/main/folder2/subFolder/directory5",
        "/main/folder2/subFolder/directory6",
        "/main/folder2/subFolder/directory7"
      ]
    ],
    "/main/folder3",
    [
      "/main/folder3/subFolder",
      [
        "/main/folder3/subFolder/directory4",
        "/main/folder3/subFolder/directory5",
        "/main/folder3/subFolder/directory6",
        "/main/folder3/subFolder/directory7"
      ],
      "/main/folder3/subs",
      [
        "/main/folder3/subFolderWrapper/folder1",
        [
          "/main/folder3/subs/folder1/subFolder",
          [
            "/main/folder3/subs/folder1/subFolder/directory1",
            "/main/folder3/subs/folder1/subFolder/directory2",
            "/main/folder3/subs/folder1/subFolder/directory3",
            "/main/folder3/subs/folder1/subFolder/directory4"
          ]
        ]
      ]
    ]
  ]
];

我在下面的此函数中尝试了各种逻辑,但这是我以前从未见过的不同的树实现。似乎需要应用某种作弊方法。因为我知道两种数组。其中一个是平面,也称为一维,另一个是二维数组。

function traverse(item) {
  for(let index in item){

    if (Array.isArray(item[index])) {
        // logic for creating nested array
        traverse(item[index]);
     }
     else {
         // logic for non array strings
     }
  }
} 

计算嵌套调用递归函数发生的时间。从项目的当前索引中减去或添加到depthCounter变量中,以到达和访问BFS一样的下一个节点。

我很好奇实现此过程的最佳方法。

1 个答案:

答案 0 :(得分:4)

您可以迭代数组,并以非数组作为路径,并将其存储为嵌套数组。

function getArrays(array, path = '') {
    var temp;
    return array.map(v => Array.isArray(v)
        ? getArrays(v, temp)
        : (temp = path + (path && '/') + v)
    );
}

const directories = ["/main", ["folder", ["subFolder", ["directory1", "directory2", "directory3"]], "folder2", ["subFolder", ["directory4", "directory5"]], "folder3", ["subFolder", ["directory4", "directory5", "directory6", "directory7"], "subFolderWrapper", ["folder1", ["subFolder", ["child1", "child2", "child3", "child4"]]]]]];

console.log(getArrays(directories));
.as-console-wrapper { max-height: 100% !important; top: 0; }