深度优先遍历和广度优先遍历
怎么实现深度优先遍历和广度优先遍历?
深度优先遍历方法比较多,最简单就是递归,它的循环写法反而比较难理解(看作任务栈)
广度优先算法方法反之,无法使用递归,只能用循环来写,但是容易理解(看作任务队列)
<!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>