Javascript Tree Traversal Algorithm

后端 未结 2 788
长发绾君心
长发绾君心 2021-02-06 10:52

I need help traversing a tree structure in a depth first fashion. I can\'t come up with an algorithm to do it properly.

My input is this:

[
    [\"A\",          


        
2条回答
  •  伪装坚强ぢ
    2021-02-06 11:47

    This should do the job:

    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", "B", "C"],
      ["1", "2"],
      ["a", "b", "c", "d"]
    ];
    
    var out = traverse(inp);
    
    console.log(out);

提交回复
热议问题