美文网首页
JavaScript 二叉树

JavaScript 二叉树

作者: RulerMike | 来源:发表于2020-08-21 09:10 被阅读0次

一个基本的基于 JavaScript 的二叉树

class Node {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}

class Tree {
    constructor() {
        // 测试数据
        this.nodes = [8 ,7 ,5, 1, 3, 10, 6];
        // this.nodes = [8,3,10,1,6,14,4,7,13];
        this.root = null;
        this.init();
    }
    init() {
        this.nodes.forEach(node => {
            this.insert(node);
        })
    }
    // 插入一个新节点
    insert(key) {
        let node = new Node(key);
        if (this.root === null) {
            this.root = node;
        } else {
            this.insertNode(this.root, node);
        }
    }
    insertNode(node, newNode) {
        if (newNode.key < node.key) {
            if (node.left === null) {
                node.left = newNode;
            } else {
                this.insertNode(node.left, newNode);
            }
        }
        else {
            if (node.right === null) {
                node.right = newNode;
            } else {
                this.insertNode(node.right, newNode);
            }
        }
    }
}

const t = new Tree();

相关文章

网友评论

      本文标题:JavaScript 二叉树

      本文链接:https://www.haomeiwen.com/subject/bfufghtx.html