-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
easyeasy difficulteasy difficult
Description
<!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="root">
<ul>
<li>
<a href="">
<img src="" alt="" />
</a>
</li>
<li>
<span></span>
</li>
<li></li>
</ul>
<p></p>
<button></button>
</div>
<script src="./index.js"></script>
</body>
</html>
// 该方法是以纵向的维度对dom树进行遍历,从一个dom节点开始,一直遍历其子节点,直到它的所有子节点都被遍历完毕之后在遍历它的兄弟节点
// Depth-First Search
// 递归
function deepFirstSearch (node, nodeList = []) {
if (node) {
nodeList.push(node)
const children = node.children
for (let i = 0; i < children.length; i++) {
// 每次递归的时候将 需要遍历的节点 和 节点所存储的数组传下去
deepFirstSearch(children[i], nodeList)
}
}
return nodeList
}
// 非递归
function deepFirstSearch (node) {
let nodes = []
if (node != null) {
let stack = []
stack.push(node)
while (stack.length != 0) {
const item = stack.pop()
nodes.push(item)
const children = item.children
for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i])
}
}
}
return nodes
}
let root = document.getElementById('root')
console.log(deepFirstSearch(root))
// 该方法是以横向的维度对dom树进行遍历,从该节点的第一个子节点开始,遍历其所有的兄弟节点,再遍历第一个节点的子节点,完成该遍历之后,暂时不深入,开始遍历其兄弟节点的子节点
// breadth-first traverse
// 非递归
function breadthFirstSearch (node) {
var nodes = []
if (node != null) {
let queue = []
// 在开头增加
queue.unshift(node)
while (queue.length != 0) {
// 删除第一个
let item = queue.shift()
nodes.push(item)
const children = item.children
for (let i = 0; i < children.length; i++) {
queue.push(children[i])
}
}
}
return nodes
}
console.log(breadthFirstSearch(root))
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
easyeasy difficulteasy difficult