JavaScript实现二叉树的先序、中序及后序遍历方法(2)
js:
/**
* Created by hp on 2016/12/22.
*/
var btn = document.getElementsByTagName('input'),
preBtn = btn[0],
inBtn = btn[1],
postBtn = btn[2],
treeRoot = document.getElementsByClassName('root')[0],
divList = [],
timer = null;
window.onload=function(){
preBtn.onclick = function () {
reset();
preOrder(treeRoot);
changeColor();
}
inBtn.onclick = function () {
reset();
inOrder(treeRoot);
changeColor();
}
postBtn.onclick = function () {
reset();
postOrder(treeRoot);
changeColor();
}
}
/*先序遍历*/
function preOrder(node){
if(!(node==null)){
divList.push(node);
preOrder(node.firstElementChild);
preOrder(node.lastElementChild);
}
}
/*中序遍历*/
function inOrder(node) {
if (!(node == null)) {
inOrder(node.firstElementChild);
divList.push(node);
inOrder(node.lastElementChild);
}
}
/*后序遍历*/
function postOrder(node) {
if (!(node == null)) {
postOrder(node.firstElementChild);
postOrder(node.lastElementChild);
divList.push(node);
}
}
/*颜色变化函数*/
function changeColor(){
var i=0;
divList[i].style.backgroundColor = 'blue';
timer=setInterval(function(argument){
i++;
if(i<divList.length){
divList[i-1].style.backgroundColor="#fff";
divList[i].style.backgroundColor="blue";
}
else{
divList[divList.length-1].style.backgroundColor="#fff";
}
},500)
}
function reset(){
divList=[];
clearInterval(timer);
var divs=document.getElementsByTagName("div");
for(var i=0;i<divs.length;i++){
divs[i].style.backgroundColor="#fff";
}
}
由此可见,二叉树的遍历思想是一样的。之前一直把JS看做是写各种特效的语言,现在向来是too naive了。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。
