JavaScript实现二叉搜索树及其先序遍历、中序遍历、后序遍历

class Node{
    constructor(data,left = null,right = null){
        this.data = data;
        this.left = left;
        this.right = right;
    }
    show(){
        console.log(this.data);
        return this.data;
    }
}
class Bst{
    constructor(root = null){
        this.root = root;
    }
    insert(data){
        const node = new Node(data);
        if(this.root===null){
            this.root = node;
        }else{
            let current = this.root;
            let parent;
            while(true){
                parent = current;
                if(current.data>data){
                    current = current.left;
                    if(current===null){
                        parent.left = node;
                        break;
                    }
                }else{
                    current = current.right;
                    if(current===null){
                        parent.right = node;
                        break;
                    }
                }
            }
        }
    }
    show(){
        console.log(this.root);
        return this.root;
    }
    preOrder(node=this.root){
        if(!(node===null)){
            node.show();
            this.preOrder(node.left);
            this.preOrder(node.right);
        }
    }
    inOrder(node=this.root){
        if(!(node===null)){
            this.inOrder(node.left);
            node.show();
            this.inOrder(node.right);
        }
    }
    postOrder(node=this.root){
        if(!(node===null)){
            this.postOrder(node.left);
            this.postOrder(node.right);
            node.show();
        }
    }
}
(() => {
    const tree = new Bst();
    [23, 45, 16, 37, 3, 99, 22].forEach(node => tree.insert(node));
    tree.show();

    console.log('先序遍历');
    tree.preOrder();
    console.log('中序遍历');
    tree.inOrder();
    console.log('后序遍历');
    tree.postOrder();
})()
发布了79 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_33807889/article/details/105007867