递归与队列在深度/广度遍历中的应用
场景实例:遍历dom树
递归
深度优先
function domTreeRecuDFS(dom) {
for (const item of dom) {
if (item.innerHTML === "123") {
return item;
}
if (item.children && item.children.length) {
const value = domTreeRecuDFS(item.children);
if (value) return value;
}
}
return null;
}
广度优先
队列
深度优先
function domTreeDFS(dom) {
const queue = [...dom];
while (queue.length > 0) {
const item = queue.shift();
if (item.innerHTML === "123") {
return item;
}
if (item.children && item.children.length) {
queue.unshift(...item.children);
}
}
return null;
}
广度优先
- 队列在深、广度优先算法中差异很小
- 更改新元素进入的位置,即可调整遍历方式
function domTreeBFS(dom) {
const queue = [...dom];
while (queue.length > 0) {
const item = queue.shift();
if (item.innerHTML === "123") {
return item;
}
if (item.children && item.children.length) {
queue.push(...item.children);
}
}
return null;
}