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

本文介绍使用JavaScript实现二叉查找树的方法,包括节点定义、插入操作及三种遍历方式(中序、先序、后序)。通过具体示例演示了二叉树的构建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值