简单的遍历一个树形结构数据的几种方法、非递归方法效率最好。
1 (function (window, undefined) { 2 var treeNodes = [ 3 { 4 id: 1, 5 name: ‘1‘, 6 children: [ 7 { 8 id: 11, 9 name: ‘11‘, 10 children: [ 11 { 12 id: 111, 13 name: ‘111‘, 14 children:[] 15 }, 16 { 17 id: 112, 18 name: ‘112‘ 19 } 20 ] 21 }, 22 { 23 id: 12, 24 name: ‘12‘, 25 children: [] 26 } 27 ], 28 users: [] 29 }, 30 { 31 id: 2, 32 name: ‘2‘, 33 children: [ 34 { 35 id: 22, 36 name: ‘22‘, 37 children: [] 38 } 39 ] 40 } 41 ]; 42 43 //递归实现 44 var parseTreeJson = function(treeNodes){ 45 var treeNodes = treeNodes || {}; 46 47 for (var i = 0, len = treeNodes.length; i < len; i++) { 48 49 var childs = treeNodes[i].children; 50 51 console.log(treeNodes[i].id); 52 53 if(childs && childs.length > 0){ 54 parseTreeJson(childs); 55 } 56 } 57 }; 58 59 console.log(‘------------- 递归实现 ------------------‘); 60 parseTreeJson(treeNodes); 61 62 //非递归广度优先实现 63 var iterator1 = function (treeNodes) { 64 var stack = []; 65 66 if (!treeNodes || !treeNodes.length) return; 67 68 //先将第一层节点放入栈 69 for (var i = 0, len = treeNodes.length; i < len; i++) { 70 stack.push(treeNodes[i]); 71 } 72 73 var item; 74 75 while (stack.length) { 76 item = stack.shift(); 77 78 console.log(item.id); 79 80 //如果该节点有子节点,继续添加进入栈底 81 if (item.children && item.children.length) { 82 //len = item.children.length; 83 84 // for (i = 0; i < len; i++) { 85 // stack.push(item.children[i]); 86 // } 87 88 stack = stack.concat(item.children); 89 } 90 } 91 }; 92 93 console.log(‘------------- 非递归广度优先实现 ------------------‘); 94 iterator1(treeNodes); 95 96 //非递归深度优先实现 97 var iterator2 = function (treeNodes) { 98 var stack = []; 99 100 if (!treeNodes || !treeNodes.length) return; 101 102 //先将第一层节点放入栈 103 for (var i = 0, len = treeNodes.length; i < len; i++) { 104 stack.push(treeNodes[i]); 105 } 106 107 var item; 108 109 while (stack.length) { 110 item = stack.shift(); 111 112 console.log(item.id); 113 114 //如果该节点有子节点,继续添加进入栈顶 115 if (item.children && item.children.length) { 116 // len = item.children.length; 117 118 // for (; len; len--) { 119 // stack.unshift(item.children[len - 1]); 120 // } 121 stack = item.children.concat(stack); 122 } 123 } 124 }; 125 126 console.log(‘------------- 非递归深度优先实现 ------------------‘); 127 iterator2(treeNodes); 128 })(window);
时间: 2024-11-05 14:56:31