遍歷一個樹形結構數據的幾種方法、非遞歸方法效率最好。
(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);
複製代碼