<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="d1">
<div id="d2">
<div class="cc1"></div>
<div class="cc5"></div>
</div>
<div class="cc3">
<div class="cc4"></div>
</div>
</div>
<div id="d3">
<div id="d4"></div>
<div id="d5">
<di id="d6"></di>
</div>
</div>
<span id="s1">
<a id="a1" href=""></a>
</span>
</body>
<script>
//深度优先遍历
function dfc(root) {
if (root == null) return []
let result = []
let nodeStack = []
nodeStack.push(root)
while (nodeStack.length > 0) {
let n = nodeStack.pop()
result.push(n)
//反向进栈
if (n.children) {
nodeStack.push(...Array.from(n.children).reverse())//DOM元素的children并不是数组类型,先转成数组
}
}
return result
}
//广度优先 同一个维度从上到下,从左到右遍历完()
function bfc(root) {
if (root == null) return []
let result = []
let nodeQueue = []//队列先进先出
nodeQueue.push(root)
while (nodeQueue.length > 0) {
let n = nodeQueue.shift()
result.push(n)
if (n.children) {
nodeQueue.push(...n.children)
}
}
return result
}
//广度优先 这种比较好理解一点
function guanduyouxian(root) {
if (root == null) return []
let result = [root]
for (let i = 0; i < result.length; i++) {
if (result[i].children) {
result.push(...result[i].children)
}
}
return result
}
//深度优先遍历
function shendu(root, result = []) {
result.push(root)
if(root.children) {
Array.from(root.children).forEach(item => {
shendu(item, result)
});
}
return result
}
console.log(guanduyouxian(document.body));
console.log(bfc(document.body));
console.log(dfc(document.body));
console.log(shendu(document.body));
</script>
</html>