JavaScript和树(一)

任务描述

  • 参考示例图,在页面中展示一颗二叉树的结构
  • 提供一个按钮,显示开始遍历,点击后,以动画的形式呈现遍历的过程
  • 二叉树的遍历算法和方式自定,前序中序后序皆可,但推荐能够提供多种算法的展现(增长多个按钮,每一个按钮对应不一样的算法)
  • 当前被遍历到的节点作一个特殊显示(好比不一样的颜色)
  • 每隔一段时间(500ms,1s等时间自定)再遍历下一个节点

 

 

先制做一个二叉树的结构和按钮组html

经过flex布局,node

justify-content: center;//水平居中

align-items: center;//垂直居中

 

而后设计遍历,http://www.javashuo.com/article/p-vuxboynr-p.html有关遍历介绍git

须要将树结构进行遍历,显示出遍历的颜色github

首先进行树的遍历,把遍历顺序记录在数组中,而后根据数组顺序,进行颜色变化算法

 

//先序遍历

function preOrder(node){

    if(!node == null){

        putstr(node.show()+ " ");

        preOrder(node.left);

        preOrder(node.right);

    }

}

//前序遍历

           function preOrder(node){

                 if(node !=null){

                      data.push(node);

                preOrder(node.firstElementChild);

                preOrder(node.lastElementChild);

                 }

           }

 

head取出数组中的节点数据;并将对应的节点的颜色进行修改segmentfault

head = data.shift();//删除并返回数组的第一个元素

                 if(head){

                      head.style.backgroundColor = "#ff0000";

                      timer = setTimeout(function(){

                            head.style.backgroundColor = "#fff";

                            show();

                      },500);

                 }

 

完整:https://github.com/moeeliu/ife/blob/master/js7.html数组

相关文章
相关标签/搜索