js—深度优先遍历(DFS)和广度优先遍历(BFS)
<div id="root"> <ul> <li> <a href=""> <img src="" alt=""> </a> </li> <li> <span></span> </li> <li> </li> </ul> <p></p> <button></button> </div>
递归 深度优先
function deepSearch(node, nodeList = []) { if(node) { const child = node.children; nodeList.push(node); for(let i=0;i<child.length;i++){ deepSearch(child[i], nodeList); } } return nodeList; } const nodeList = []; const a = deepSearch(document.getElementById('root'), nodeList);
非递归 深度优先
function deepSearch1(node) { const nodeList = []; const stack = []; if(node) { stack.push(node); while(stack.length) { const item = stack.pop(); nodeList.push(item); for(let i = item.children.length -1;i>-1;i--){ stack.push(item.children[i]); } } } return nodeList; } const a = deepSearch1(document.getElementById('root'));
递归 广度优先
const nodeList = []; function breadthSearch(node, nodeList = []) { if(!(node == null)) { nodeList.push(node); breadthSearch(node.nextElementSibling, nodeList); breadthSearch(node.firstElementChild, nodeList); } return nodeList; } const a = breadthSearch(document.getElementById('root'), nodeList);
非递归 广度优先
function breadthSearch1(node) { const nodeList = []; const queue = []; if(node) { queue.unshift(node); while(queue.length) { const item = queue.shift(); nodeList.push(item); for(let i = 0;i<item.children.length;i++){ queue.push(item.children[i]); } } } return nodeList; } const a = breadthSearch1(document.getElementById('root'));