マルチツリーを巡回(再帰的、非再帰的、広さ優先、深さ優先)
3352 ワード
単純なツリー構造データを遍歴するいくつかの方法、非再帰的方法が一番効率的です.
(function (window, undefined) {
var treeNodes = [
{
id: 1,
name: '1',
children: [
{
id: 11,
name: '11',
children: [
{
id: 111,
name: '111',
children:[]
},
{
id: 112,
name: '112'
}
]
},
{
id: 12,
name: '12',
children: []
}
],
users: []
},
{
id: 2,
name: '2',
children: [
{
id: 22,
name: '22',
children: []
}
]
}
];
//
var parseTreeJson = function(treeNodes){
if (!treeNodes || !treeNodes.length) return;
for (var i = 0, len = treeNodes.length; i < len; i++) {
var childs = treeNodes[i].children;
console.log(treeNodes[i].id);
if(childs && childs.length > 0){
parseTreeJson(childs);
}
}
};
console.log('------------- ------------------');
parseTreeJson(treeNodes);
//
var iterator1 = function (treeNodes) {
if (!treeNodes || !treeNodes.length) return;
var stack = [];
//
for (var i = 0, len = treeNodes.length; i < len; i++) {
stack.push(treeNodes[i]);
}
var item;
while (stack.length) {
item = stack.shift();
console.log(item.id);
// ,
if (item.children && item.children.length) {
//len = item.children.length;
// for (i = 0; i < len; i++) {
// stack.push(item.children[i]);
// }
stack = stack.concat(item.children);
}
}
};
console.log('------------- ------------------');
iterator1(treeNodes);
//
var iterator2 = function (treeNodes) {
if (!treeNodes || !treeNodes.length) return;
var stack = [];
//
for (var i = 0, len = treeNodes.length; i < len; i++) {
stack.push(treeNodes[i]);
}
var item;
while (stack.length) {
item = stack.shift();
console.log(item.id);
// ,
if (item.children && item.children.length) {
// len = item.children.length;
// for (; len; len--) {
// stack.unshift(item.children[len - 1]);
// }
stack = item.children.concat(stack);
}
}
};
console.log('------------- ------------------');
iterator2(treeNodes);
})(window);