首页 > 语言 > JavaScript > 正文

JavaScript实现二叉树的先序、中序及后序遍历方法详解

2024-05-06 15:25:06
字体:
来源:转载
供稿:网友

本文实例讲述了JavaScript实现二叉树的先序、中序及后序遍历方法。分享给大家供大家参考,具体如下:

之前学数据结构的时候,学了二叉树的先序、中序、后序遍历的方法,并用C语言实现了,下文是用js实现二叉树的3种遍历,并以动画的形式展现出遍历的过程。

整个遍历过程还是采用递归的思想,原理很粗暴也很简单

先序遍历的函数:

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)}

核心代码如上,本来想写深度优先遍历和广度优先遍历。后来发现二叉树深度优先遍历和先序遍历相同。改日总结一下树的BFS和DFS。

全部代码如下:

<!DOCTYPE html><html><head lang="en">  <meta charset="UTF-8">  <title></title>  <style>    .root{      display: flex;      padding: 20px;      width: 1000px;      height: 300px;border: 1px solid #000000;      margin: 100px auto;      margin-bottom: 10px;      justify-content: space-between;    }    .child_1{      display: flex;      padding: 20px;      width: 450px;      height: 260px;border: 1px solid red;      justify-content: space-between;    }    .child_2{      display: flex;      padding: 20px;      width: 170px;      height: 220px;border: 1px solid green;      justify-content: space-between;    }    .child_3{      display: flex;      padding: 20px;      width: 35px;      height: 180px;border: 1px solid blue;      justify-content: space-between;    }    input{      margin-left: 100px;      width: 60px;      height: 40px;      font:20px italic;    }  </style></head><body><div class="root">  <div class="child_1">    <div class="child_2">      <div class="child_3"></div>      <div class="child_3"></div>    </div>    <div class="child_2">      <div class="child_3"></div>      <div class="child_3"></div>    </div>  </div>  <div class="child_1">    <div class="child_2">      <div class="child_3"></div>      <div class="child_3"></div>    </div>    <div class="child_2">      <div class="child_3"></div>      <div class="child_3"></div>    </div>  </div></div><input type="button" value="先序"><input type="button" value="中序"><input type="button" value="后序"><script type="text/javascript" src="遍历.js"></script></body></html>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选