二叉树遍历前端实现

三种方式遍历二叉树
从根节点开始,判断它是否有第一个子节点和最后一个子节点,递归。将节点按顺序放入数组,在设置定时器,按顺序改变div的颜色
https://github.com/Phoebe-Perry/ife_baidu_2016/tree/gh-pages/second_phase/ife-baidu_task_22




<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>遍历二叉树</title>
<style type=“text/css”>
div{
background: #fff;
}
.root{
width: 800px;
height: 270px;
padding: 30px;
border: 1px solid black;
display: flex;
justify-content: space-between;
}
.child1{
width: 320px;
height: 210px;
padding: 30px;
border: 1px solid purple;
display: flex;
justify-content: space-between;

}
.child2{
width: 120px;
height: 190px;
padding: 10px;
border: 1px solid green;
display: flex;
justify-content: space-between;
}
.child3{
width: 20px;
height: 150px;
margin: 20px;
border: 1px solid blue;
display: flex;
justify-content: space-between;
}
button{
margin: 30px;
}
</style>
</head>
<body>

<div class=“root”>
<div class=“child1”>
<div class=“child2”>
<div class=“child3”></div>
<div class=“child3”></div>
</div>
<div class=“child2”>
<div class=“child3”></div>
<div class=“child3”></div>
</div>
</div>
<div class=“child1”>
<div class=“child2”>
<div class=“child3”></div>
<div class=“child3”></div>
</div>
<div class=“child2”>
<div class=“child3”></div>
<div class=“child3”></div>
</div>
</div>
</div>
<button id=“pre”>前序</button>
<button id=“mid”>中序</button>
<button id=“last”>后序</button>
</body>
<!–<script src=”index.js” type=”text/javascript”></script>–>
<script type=“text/javascript”>
var root = document.querySelector(‘.root’);
var divList = [];
var prebtn = document.querySelector(‘#pre’);
var midbtn = document.querySelector(‘#mid’);
var lastbtn = document.querySelector(‘#last’);
var div = document.getElementsByTagName(‘div’);


prebtn.onclick = function(){
reset();
preOrder(root);
changeColor();
}

midbtn.onclick = function(){
reset();
midOrder(root);
changeColor();
}

lastbtn.onclick = function(){
reset();
lastOrder(root);
changeColor();
}

function preOrder(node){
if(node){
divList.push(node);
preOrder(node.firstElementChild);
preOrder(node.lastElementChild);
}
}

function midOrder(node){
if(node){
midOrder(node.firstElementChild);
divList.push(node);
midOrder(node.lastElementChild);
}
}

function lastOrder(node){
if(node){
lastOrder(node.firstElementChild);
lastOrder(node.lastElementChild);
divList.push(node);
}
}

function reset(){
for(var i = 0;i<div.length;i++){
div[i].style.backgroundColor = ‘#fff’;
}
divList = [];
clearInterval(timer);
}
var timer;
function changeColor(){
var i = 0;
divList[0].style.backgroundColor = ‘purple’;
timer = setInterval(function(){
i++;
console.log(i);
if(i<divList.length){
divList[i-1].style.backgroundColor = ‘#fff’;
divList[i].style.backgroundColor = ‘purple’;
}else{
divList[i-1].style.backgroundColor = ‘#fff’;
clearInterval(timer);
}
},500)
}
</script>
</html>