what、how
- 深度优先遍历:找到一个节点然后把它的后辈都找出来,最常用递归法
- 广度优先遍历:找到一个节点然后把它的同级节点找出来放前面孩子放后面,最常用 while 循环
如下实例输出结果区别如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="parent">
<div class="child-1">
<div class="child-1-1"></div>
<div class="child-1-2"></div>
</div>
<div class="child-2">
<div class="child-2-1"></div>
<div class="child-2-2"></div>
<div class="child-2-3">
<div class="child-2-3-1"></div>
<div class="child-2-3-2"></div>
</div>
</div>
<div class="child-3"></div>
</div>
<script>
const eles = document.getElementsByClassName('parent')[0]
console.log(deepTraversal1(eles))
console.log(deepTraversal2(eles))
console.log(widthTraversal1(eles))
function deepTraversal1(node, arr = []) {
if(node) {
arr.push(node)
if(node.children) {
for(let i = 0; i < node.children.length; i++) {
deepTraversal1(node.children[i], arr)
}
}
}
return arr
}
function deepTraversal2(node) {
let arr = []
if(node) {
arr.push(node)
if(node.children) {
for(let i = 0; i < node.children.length; i++) {
arr = arr.concat(deepTraversal2(node.children[I]))
}
}
}
return arr
}
function widthTraversal1(node) {
let nodes = []
let queue = []
queue.push(node)
while(queue.length) {
let first = queue.shift()
if(first) {
nodes.push(first)
if(first.children) {
for(let i = 0; i < first.children.length; i++) {
queue.push(first.children[i])
}
}
}
}
return nodes
}
</script>
</body>
</html>