怎麼實現深度優先遍歷和廣度優先遍歷?html
深度優先遍歷方法比較多,最簡單就是遞歸,它的循環寫法反而比較難理解(看做任務棧)node
廣度優先算法方法反之,沒法使用遞歸,只能用循環來寫,可是容易理解(看做任務隊列)算法
<!DOCTYPE html> <html lang="en"> <body> <div id="parent"> <div class="child-1"> <div class="child-1-1"></div> <div class="child-1-2"></div> <div class="child-1-3"></div> </div> <div class="child-2"> <div class="child-2-1"></div> <div class="child-2-2"></div> <div class="child-2-3"></div> </div> <div class="child-3"> <div class="child-3-1"></div> <div class="child-3-2"></div> <div class="child-3-3"></div> </div> </div> <script> // 自帶數組的遞歸 function recursive(dom) { let nodes = [] if (dom) { nodes.push(dom) let children = dom.children Array.from(children).forEach(item => { nodes = nodes.concat(recursive(item)) }) } return nodes } // 外帶數組的遞歸 function recursive2(dom, nodes) { if (dom) { nodes.push(dom) let children = dom.children Array.from(children).forEach(item => { recursive2(item, nodes) }) } } // 使用棧來實現深度優先 function deepTraveral(dom) { let nodes = [] let stack = [] if (dom) { stack.push(dom) while(stack.length) { dom = stack.pop() nodes.push(dom) let children = dom.children for (let i = children.length - 1; i >= 0; i --) { stack.push(children[i]) } } } return nodes } // 使用隊列實現廣度優先 function widthTraveral(dom) { let nodes = [] let stack = [] if (dom) { stack.push(dom) while(stack.length) { dom = stack.shift() nodes.push(dom) let children = dom.children Array.from(children).forEach(item => { stack.push(item) }) } } return nodes } const parent = document.getElementById('parent') console.log(recursive(parent)) let arr = [] recursive2(parent, arr) console.log(arr) console.log(deepTraveral(parent)) console.log(widthTraveral(parent)) </script> </body> </html>