[数据结构]javascript实现二叉查找树

来源:互联网 发布:激战2人类女捏脸数据库 编辑:程序博客网 时间:2024/06/08 01:57

javascript实现二叉树的原理:

  //二叉查找树是由节点组成,所以我们首先要定义一个Node类,包含了数据、左右节点、读取数据的方法;   function Node(data, left, right){    this.data = data;    this.left = left;    this.right = right    this.show = show;   }   function show(){    return this.data   }   //定义树BST   function BST(){    this.root = null;    this.insert = insert;   }   function insert(data){              var newNode = new Node(data, null, null);              if (this.root == null){                 this.root = newNode;              } else {                    var current = this.root;                    var parent;                    while (true){                        parent = current;                        if (current.data > data ){                            current = current.left;                            if (current == null){                              parent.left = newNode;                              break;                            }                         } else {                            current = current.right;                            if (current == null){                                parent.right = newNode;                                break;                            }                         }                   }              }        }   //中序遍历   function inOrder(node){      if (node){        inOrder(node.left);        console.log(node.data);        inOrder(node.right);      }   }   //先序遍历   function preOrder(node){      if (node){        console.log(node.data);        preOrder(node.left);        preOrder(node.right);      }   }   //后序遍历   function postOrder(node){      if (node){        postOrder(node.left);        postOrder(node.right);        console.log(node.data);      }   }    //初始化一棵树,然后中序遍历    var bst = new BST();    bst.insert(23);    bst.insert(122);    bst.insert(112);    bst.insert(123);    bst.insert(12);    bst.insert(2);    bst.insert(10);    console.log('中序遍历:');//2,10,12,23,112,122,123    inOrder(bst.root);    console.log('先序遍历:');//23,12,2,10,122,112,123    preOrder(bst.root);    console.log('后序遍历:');    postOrder(bst.root);//10,2,12,112,123,122,23

用js二叉树实现的demo

https://shaojinghong.github.io/js-DataStructure/

原创粉丝点击