JavaScript中利用二叉树对数组进行排序

二叉树和二叉搜索树

二叉树中的节点最多只能有两个子节点:一个是左侧子节点,另一个是右侧子节点。
二叉搜索树(BST)是二叉树中的一种,但是它只允许在左侧节点存储比父节点小的值,在右侧几点存储比节点大(或相等)的值。
可以利用BST的这种特性,对数组进行排序

class Node{
    constructor(key){
        this.key = key;
        this.left = null;
        this.right= null;
    }
}
class BinarySearchTree{
    constructor(){
        this.root = null;
        this.length = 0;
    }
    insert(key){
        const node = new Node(key);
        const insertNode = (root, node) => {
            if(root.key>node.key){
                root.left ? insertNode(root.left, node) : root.left = node;
            }else {
                root.right ? insertNode(root.right, node) : root.right = node;
            }
        }
        if(this.root){
            insertNode(this.root, node);
        }else {
            this.root = node;
        }
        this.length++;
        return this;
    }
    // 二叉树中序遍历
    middleOrderTree(){
        var result = [];
        const middleOrder = (root) => {
            root.left && middleOrder(root.left);
            result.push(root.key);
            root.right && middleOrder(root.right);
            return result;
        };
        return middleOrder(this.root);
    }
    arrayToTree(arr){
        for(var i=0;i<arr.length;i++){
            this.insert(arr[i]);
        }
        return this;
    }
}

二叉树共有三种遍历方法:
先序遍历:节点本身–>左侧子节点–>右侧子节点
中序遍历:左侧子节点–>节点本身–>右侧子节点
后序遍历:左侧子节点–>节点本身–>右侧子节点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值