思路 前四次都执行函数A,得到1,2,3,4,添加4,3,第五次执行B,得到4,添加4,接着添加2,第六次执行函数B,得到3,在添加3之前第七次执行函数A,得到4,添加4,在添加3,,第八次执行函数B,得到4,添加4,在添加1,第九次执行函数B,得到2,在添加之前第10次执行函数A;得到3,第11次执行函数A,得到4,添加4,3,添加3后立即第12次执行函数B,得到4,储存为2,4,先添加4,再添加2,接着第13次执行函数B,得到3,在添加3之前第14次执行函数A,得到4,添加4,再添加3,最后一次执行函数B,得到4,添加4
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Binary Tree</title> <link rel="stylesheet" href="styles/reset.css"> <link rel="stylesheet" href="styles/main.css"> </head> <body> <div class="box-container"> <div class="level-1" id="top-level"> <div class="level-2"> <div class="level-3"> <div class="level-4"></div> <div class="level-4"></div> </div> <div class="level-3"> <div class="level-4"></div> <div class="level-4"></div> </div> </div> <div class="level-2"> <div class="level-3"> <div class="level-4"></div> <div class="level-4"></div> </div> <div class="level-3"> <div class="level-4"></div> <div class="level-4"></div> </div> </div> </div> </div> <div class="btn-container"> <input type="button" value="前序遍历" id="preorder"> <input type="button" value="中序遍历" id="inorder"> <input type="button" value="后序遍历" id="postorder"> </div> <script> var traverse = []; var timer; //中序遍历 function inOrder(tree) { console.log(tree); if (tree !== null) { inOrder(tree.firstElementChild); traverse.push(tree); inOrder(tree.lastElementChild); } } window.onload = function () { document.getElementById("inorder").onclick = function () { clearTraverse(); inOrder(domTree); animate(traverse); console.log(traverse); }; }; //清理前一个遍历 function clearTraverse() { var allDiv = document.getElementsByTagName("div"); for (var i = 0; i < allDiv.length; i++) { allDiv[i].setAttribute("background","#fff"); } clearInterval(timer); traverse = []; } //将遍历结果用动画展示 function animate(traverse) { var i = 0; traverse[i].style.background = "#fec8b0"; timer = setInterval(function () { i++; if (i < traverse.length) { traverse[i - 1].style.background = "#fff"; traverse[i].style.background = "#fec8b0" } else { clearTraverse(); traverse[traverse.length - 1].style.background = "#fff"; } },500); }