廣度優先遍歷,先遍歷全部鄰接點,再往下遍歷,按照dom樹轉爲而二叉樹有序遍歷以下:
// 廣度優先有序遍歷:先訪問全部鄰節點
function Bfs(node, isChild){
var firstChild = isChild ? node.firstElementChild : node.nextElementSibling;
if (firstChild) {
console.log(firstChild)
if (firstChild.nextElementSibling) {
Bfs(firstChild, 0)
} else {
Bfs(firstChild.parentNode.firstElementChild, 1)
}
} else {
if (node.parentNode.nextElementSibling) {
Bfs(node.parentNode.nextElementSibling, 1)
} else {
console.log('遍歷結束' )
}
}
}
Bfs(document.getElementById('root' ), 1)
複製代碼
// 廣度優先遍歷:非遞歸遍歷,按照隊列的先進先出
function Bfs(node){
let nodes = []
let stack = []
if (node) {
stack.push(node)
while (stack.length) {
let item = stack.shift()
let children = item.children
nodes.push(item)
for (let i =0;i<children.length;i++) {
stack.push(children[i])
}
}
}
return nodes
}
let nodes = Bfs(document.getElementById('root' ).firstElementChild)
console.log(nodes)
複製代碼
深度優先遍歷:分爲三種,先序(根-左-右),中序(左-根-右),後序(左-右-根)
//深度有序優先遍歷:先序遍歷根-左-右
function LeftDfs(node,isChild){
var firstChild = isChild ? node.firstElementChild : node.nextElementSibling;
if (firstChild) {
console.log(firstChild)
if (firstChild.firstElementChild) { // 先判斷子節點
LeftDfs(firstChild,1)
} else if (firstChild.nextElementSibling){ // 在判斷子節點的鄰節點
LeftDfs(firstChild,0)
} else {
LeftDfs(firstChild.parentNode, 0)
}
} else {
console.log('遍歷結束' )
}
}
LeftDfs(document.getElementById('root' ),1)
複製代碼
//非遞歸遍歷,按照棧
let LeftDfs= (node) => {
let stack = []
let nodes = []
if (node) {
// 推入當前處理的node
stack.push(node)
while (stack.length) {
let item = stack.pop()//出棧
let children = item.children
nodes.push(item)
for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i])
}
}
}
return nodes
}
//深度優先遍歷:遞歸遍歷
function LeftDfs(node, nodeTree){
if (node !== null) {
nodeTree.push(node)
for (let i =0; i<node.children.length;i++) {
LeftDfs(node.children[i],nodeTree)
}
}
return nodeTree
}
let node = LeftDfs(document.getElementById('root' ).firstElementChild, [])
console.log(node)
複製代碼