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