Javascript树遍历算法

前端之家收集整理的这篇文章主要介绍了Javascript树遍历算法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要以深度优先的方式遍历树结构的帮助.我无法想出一个算法来正确地做到这一点.

我的意见是这样的:

[
    ["A","B","C"],["1","2"],["a","b","c","d"]
]

输出应采取以下形式:

[
    "A/1/a","A/1/b","A/1/c","A/1/d","A/2/a","A/2/b","A/2/c","A/2/d","B/1/a","B/1/b","B/1/c","B/1/d","B/2/a","B/2/b","B/2/c","B/2/d","C/1/a","C/1/b","C/1/c","C/1/d","C/2/a","C/2/b","C/2/c","C/2/d"
]

解决方法

这应该做的工作:
function traverse(arr) {
  var first = arr[0];
  var ret = [];
  if (arr.length == 1) {
    for (var i = 0; i < first.length; i++) {
      ret.push(first[i]);
    }
  } else {
    for (var i = 0; i < first.length; i++) {
      var inn = traverse(arr.slice(1));
      for (var j = 0; j < inn.length; j++) {
        ret.push(first[i] + '/' + inn[j]);
      }
    }
  }
  return ret;
}

var inp = [
  ["A","d"]
];

var out = traverse(inp);

console.log(out);
原文链接:https://www.f2er.com/js/240877.html

猜你在找的JavaScript相关文章