本文主要介绍了javascript实现二叉树的先序、中序及后序遍历方法,结合实例形式总结分析了javascript二叉树的先序、中序及后序遍历实现方法与相关操作注意事项,需要的朋友可以参考下,希望能帮助到大家。
本文实例讲述了JavaScript实现二叉树的先序、中序及后序遍历方法。分享给大家供大家参考,具体如下:
之前学数据结构的时候,学了二叉树的先序、中序、后序遍历的方法,并用C语言实现了,下文是用js实现二叉树的3种遍历,并以动画的形式展现出遍历的过程。
整个遍历过程还是采用递归的思想,原理很粗暴也很简单
先序遍历的函数:
立即学习“Java免费学习笔记(深入)”;
function preOrder(node){
if(!(node==null)){
pList.push(node);
preOrder(node.firstElementChild);
preOrder(node.lastElementChild);
}
}中序遍历的函数:
function inOrder(node) {
if (!(node == null)) {
inOrder(node.firstElementChild);
pList.push(node);
inOrder(node.lastElementChild);
}
}后序遍历的函数:
function postOrder(node) {
if (!(node == null)) {
postOrder(node.firstElementChild);
postOrder(node.lastElementChild);
pList.push(node);
}
}颜色变化函数:
function changeColor(){
var i=0;
pList[i].style.backgroundColor = 'blue';
timer=setInterval(function(argument){
i++;
if(i核心代码如上,本来想写深度优先遍历和广度优先遍历。后来发现二叉树深度优先遍历和先序遍历相同。改日总结一下树的BFS和DFS。
ecshop多接口支付插件
此插件安装后,ECSHOP程序即可拥有:网银、信用卡、银联卡、支付宝、微信等多家支付接口,实现ECSHOP程序PC支付及WAP手机扫码支付等。此插件由“中云支付”提供。安装方法:第一步:备份ECSHOP源程序文件。第二步:上传压缩包中的includes\modules\payment目录下的cnzyzf.php、cod.php、syl.php文件和languages\zh_cn\payment目录
下载
全部代码如下:
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],
pList = [],
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)){
pList.push(node);
preOrder(node.firstElementChild);
preOrder(node.lastElementChild);
}
}
/*中序遍历*/
function inOrder(node) {
if (!(node == null)) {
inOrder(node.firstElementChild);
pList.push(node);
inOrder(node.lastElementChild);
}
}
/*后序遍历*/
function postOrder(node) {
if (!(node == null)) {
postOrder(node.firstElementChild);
postOrder(node.lastElementChild);
pList.push(node);
}
}
/*颜色变化函数*/
function changeColor(){
var i=0;
pList[i].style.backgroundColor = 'blue';
timer=setInterval(function(argument){
i++;
if(i由此可见,二叉树的遍历思想是一样的。之前一直把JS看做是写各种特效的语言,现在向来是too naive了。
相关推荐:










