[Javascript Data Structures] Binary Tree二叉树 & BRT (1)

(1) Binary Tree二叉树

 空树 或者是 每个结点最多只有2个子树

满二叉树 : 一颗深度为K and 有(2 的 k次幂 -1)个结点的树
完全二叉树:标号从1-n 一一对应

来自网上 图片位置
这里写图片描述


(2) Binary Search Tree 二叉搜索树

父节点的值>左子树的值    父节点的值<右子树的值

这里写图片描述

<script type="text/javascript">

   function BST(){
       function Node(data){
         this.data=data;
         this.left=null;
         this.right=null;
       }
       var root=null;
       this.insert=function(data){
         var node=new Node(data);
         //如果数没有根节点
         if (root==null) {
             root=node;
         }else{ 
             insertnode(root,node);
         }
       }
       var insertnode=function(root,node){
         if (root.data>=node.data) {//Left
            if (root.left==null) {//left tree 
                root.left=node;
            }else{
                insertnode(root.left,node);
            }
         }else{//right
            if (root.right==null) {
                root.right=node;
            }else{
                insertnode(root.right,node);
            }
         }
       }

       this.findall=function(){
        if (root===null) {
             console.log("Don't have tree");
          }else{
            console.log(root);
             //findnode(root);
           }
       }


       this.min=function(){
         if (root===null) {
             console.log("Don't have tree");
          }else{  
             findmin(root);
           }
       }

       var findmin=function(root){
          if (root.left!==null) {
             if (root.left.left===null) {
                 console.log(root.left.data);
             }else{
                 findmin(root.left);
             }
          }else{//right
             if (root.right.left===null) {
                 console.log(root.right.data);
             }else{
                 findmin(root.right);
             }
          }
       }
   }


    var bst=new BST();
    bst.findall();
    bst.insert(11);
    bst.insert(15);
    bst.insert(7);
    bst.insert(5);
    bst.insert(9);
    bst.insert(20);  
    bst.findall();
    bst.min();

</script>

Result:
这里写图片描述

这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值