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;
    }
}

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

猜你喜欢

转载自blog.csdn.net/csm0912/article/details/83989397