通过树递归来创建面包屑列表

时间:2015-11-05 17:23:00

标签: javascript recursion

我有一个数据树,我正在尝试创建一个递归函数,将树中的每个路径添加为字符串数组,以便更好地理解递归。我不确定为什么我的方法没有产生期望

var tree = {
	"name": "home",
	"children": [
		{
			"name": "cars",
			"children": [
				{
					"name": "ford",
					"children": [
						{
							"name": "mustang"
						},
						{
							"name": "explorer"
						}
					]
				}
			]
		},
		{
			"name": "food",
			"children": [
				{
					"name": "pizza"
				}
			]
		}
	]
};

var list = [];
var path = [];

function traverse(node) {
    if (node.name) { 
        path.push(node.name) 
    }
    
    if (!node.children) { 
        if (path.length) {
            list.push(path);
        }
        return; 
    } else {
     node.children.forEach(function(item) {
       traverse(item); 
     });  
    }
}

traverse(tree);
console.log(list);

我想要创建的输出是:

[
    ["home"],
    ["home", "cars"],
    ["home", "cars", "ford"],
    ["home", "cars", "ford", "mustang"],
    ["home", "cars", "ford", "explorer"],
    ["home", "food"],
    ["home", "food", "pizza"]
]

2 个答案:

答案 0 :(得分:3)

您在所有迭代中修改相同的path数组。你应该复制它:

var list = [];
function traverse(node, path) {
  if ( !path )
    path = [];
  if (node.name) {
    path.push(node.name)
  }
  list.push(path);
  if (node.children) {
    node.children.forEach(function(item) {
      traverse(item, path.slice());
    });
  }
}
traverse(tree, []);

答案 1 :(得分:2)

我已更正您的代码,此解决方案将path变量从一个函数调用复制到另一个:



var tree = {
  "name": "home",
  "children": [{
    "name": "cars",
    "children": [{
      "name": "ford",
      "children": [{
        "name": "mustang"
      }, {
        "name": "explorer"
      }]
    }]
  }, {
    "name": "food",
    "children": [{
      "name": "pizza"
    }]
  }]
};

var path = [];

var list = [];
function traverse(node, path) {
  if ( !path )
    path = [];
  if (node.name) {
    path.push(node.name)
  }
  list.push(path);
  if (node.children) {
    node.children.forEach(function(item) {
      traverse(item, path.slice());
    });
  }
  document.write(JSON.stringify(path )+ '<br>')
}
traverse(tree, []);
&#13;
&#13;
&#13;