一个基本的基于 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();