首先我们要知道前序遍历:中序遍历,后序遍历的概念:
前序遍历:从双亲节点开始,遍历左树,再遍历右树;
中序遍历:从左树开始,再遍历双亲节点,最后遍历右树;
后序遍历:从左树开始,再遍历右树,最后遍历双亲节点;
核心算法很简单:创建一个数组,将当前的节点递归,算法不同处只是在于数组加入node节点的次序不一样:
// 前序算法
function beforeErgodic(node) {
if (!!node) {
arr.push(node);
beforeErgodic(node.firstElementChild);
beforeErgodic(node.lastElementChild);
}
}
// 中序算法
function middleErgodic(node) {
if (!!node) {
middleErgodic(node.firstElementChild);
arr.push(node);
middleErgodic(node.lastElementChild);
}
}
// 后序算法
function afterErgodic(node) {
if (!!node) {
afterErgodic(node.firstElementChild);
afterErgodic(node.lastElementChild);
arr.push(node);
}
}
完整的代码展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
button {
background: blue;
width: 100px;
height: 60px;
color: white;
}
html, body {
width: 100%;
height: 100%;
}
.wrapper {
display: flex;
width: 100%;
align-items: center;
height: 90%;
}
.wrapper > div {
flex: 1;
width: 0;
}
.wrapper div {
height: 50%;
align-items: center;
display: flex;
flex: 1;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="wrapper">
<div>
<div>
<div>
</div>
<div>
</div>
</div>
<div>
<div>
</div>
<div>
</div>
</div>
</div>
<div>
<div>
<div>
</div>
<div>
</div>
</div>
<div>
<div>
</div>
<div>
</div>
</div>
</div>
</div>
<button>前序</button>
<button>中序</button>
<button>后序</button>
<script src="算法结构.js"></script>
<script>
let wrapper = document.querySelector(".wrapper");
let btn0 = document.querySelectorAll("button")[0];
let btn1 = document.querySelectorAll("button")[1];
let btn2 = document.querySelectorAll("button")[2];
let arr = [];
// 前序算法
function beforeErgodic(node) {
if (!!node) {
arr.push(node);
beforeErgodic(node.firstElementChild);
beforeErgodic(node.lastElementChild);
}
}
// 中序算法
function middleErgodic(node) {
if (!!node) {
middleErgodic(node.firstElementChild);
arr.push(node);
middleErgodic(node.lastElementChild);
}
}
// 后序算法
function afterErgodic(node) {
if (!!node) {
afterErgodic(node.firstElementChild);
afterErgodic(node.lastElementChild);
arr.push(node);
}
}
let showC = ['red', 'blue', 'green', 'yellow', 'orange', '#ccc', '#eee', 'purple'];
showC = showC.concat(showC);
function ArrToDomShow() {
arr.forEach(function (dom, index) {
setTimeout(function () {
console.log(showC[index] + index);
dom.style.background = showC[index]
}, index * 300)
})
}
btn0.addEventListener("click", function () {
setTimeout(function () {
arr = [];
beforeErgodic(wrapper);
ArrToDomShow();
}, 0)
});
btn1.addEventListener("click", function () {
setTimeout(function () {
arr = [];
middleErgodic(wrapper);
ArrToDomShow();
}, 0)
});
btn2.addEventListener("click", function () {
setTimeout(function () {
arr = [];
afterErgodic(wrapper);
ArrToDomShow();
}, 0)
})
</script>
</body>
</html>