二叉树数据结构

1. Js二叉树数据的创建


 function Node(data,left,right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
    //定义插入对象
    function BST(){
        this.root = null;
        this.insert = insert;
        this.show = ()=>{
           console.log(this.root);
        }
    }
    function insert(data) {
        //实例化Node对象
        let n = new Node(data,null,null);
        //如果不存在节点,则此节点是根节点
        if(this.root == null){
            this.root = n;
        }else{
            //存在根节点时,定义current白能量等于根节点
            let current = this.root;
            let parent;
            while(current){
                parent = current;
                //当插入的值小于根节点的值时,将值作为左节点插入
                if(data<current.data) {
                    current = current.left;
                    if(current == null) {
                        parent.left = n;
                        break;
                    }
                }else{
                    current = current.right;
                    if(current == null){
                        parent.right = n;
                        break;
                    }
                }
            } 
        }
    }
    const bst = new BST();
    bst.insert(13);
    bst.insert(21);
    bst.insert(15);
    bst.insert(29);
    bst.insert(23);
    bst.insert(55);
    bst.show();

 

 2. 二叉树基本类型

暂无图片

 

 3. 二叉树的遍历

    二叉树的遍历分为三类:前序遍历、中序遍历和后序遍历。(补充一种层序遍历 )

前序遍历 先访问根节点,再遍历左子树,最后遍历右子树;并且在遍历左右子树时,仍需先访问根节点,然后遍历左子树,最后遍历右子树。——前序遍历(a)图( ABDHIEJKCFLMGNO )!根-左-右

中序遍历 先遍历左子树、然后访问根节点,最后遍历右子树;并且在遍历左右子树的时候。仍然是先遍历左子树,然后访问根节点,最后遍历右子树。——中序遍历(a)图( HDIBJEKALFMCNGO )!左-根-右

后序遍历 先遍历左子树,然后遍历右子树,最后访问根节点;同样,在遍历左右子树的时候同样要先遍历左子树,然后遍历右子树,最后访问根节点。——后序遍历(a)图( HIDJKEBLMFNOGCA )!左-右-根

层序遍历  先访问根节点,从上到下逐层遍历,在同一层中,按从左到右的顺序结点逐个访问。                                        ——层序遍历(a)图( ABCDEFGHJKLMNO)!

 

                                                                                                                                                       {\color{Red} by \ \ Nidhogg\cdot D\cdot Joking}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值