var tree = {
name: 'root',
children: [{
name: 'child1',
children: [{
name: 'child1_1',
children: []
}, { name: 'child1_2', children: [] }]
}, {
name: 'child2',
children: [{
name: 'child2_1',
children: []
}]
}, {
name: 'child3',
children: [{
name: 'child2_1',
children: []
}]
}]
};
複製代碼
廣度優先遍歷:javascript
function wideTraversal(node) {
var nodes = [];
if (node != null) {
var queue = [];
queue.unshift(node);
while (queue.length != 0) {
var item = queue.shift();
nodes.push(item.name);
var children = item.children;
for (var i = 0; i < children.length; i++) {
queue.push(children[i]);
}
}
}
return nodes;
}
console.log(wideTraversal(tree))
複製代碼
輸出結果:java
[ 'root','child1','child2','child3','child1_1','child1_2','child2_1','child2_1' ]node
深度優先遍歷:數組
function traverseTree(node) {
var child = node.children,
arr = [];
arr.push(node.name);
if (child) {
child.forEach(function(node) {
arr = arr.concat(traverseTree(node));
});
}
return arr;
}
console.log(traverseTree(tree))
複製代碼
輸出結果:ide
[ 'root','child1','child1_1','child1_2','child2','child2_1','child3','child2_1' ]ui
相似:spa
var data = [
{ parentId: 0, id: 1, value: '1' },
{ parentId: 3, id: 2, value: '2' },
{ parentId: 0, id: 3, value: '3' },
{ parentId: 1, id: 4, value: '4' },
{ parentId: 1, id: 5, value: '5' }
]
複製代碼
指望輸出:code
[
{id:1,value:'1',
children:[{id:4,value:'4',children:[]},
{id:5,value:'5',children:[]}]},
{id:3,value:'3',
children:[id:2,value:'2',children:[]]}]
複製代碼
代碼:cdn
var getJsonTree = function(data, parentId) {
var itemArr = [];
for (var i = 0; i < data.length; i++) {
var node = data[i];
//data.splice(i, 1)
if (node.parentId == parentId) {
var newNode = { id: node.id, value: node.value, children: getJsonTree(data, node.id) };
itemArr.push(newNode);
}
}
return itemArr;
}
console.log(getJsonTree(data, 0))
複製代碼