转载文章:JavaScript 种一颗二叉树
class Tree {
left = null;
right = null;
root = null;
constructor(_value) { this.value = _value;}
}
class Trees {
constructor() { this.root = null; }
insert(value) {this.root ? this.insertTree(this.root, new Tree(value)) : this.root = new Tree(value);}
insertTree(rootNode, newTree) {
newTree.value < rootNode.value ?
(rootNode.left ? this.insertTree(rootNode.left, newTree) : rootNode.left = newTree)
:
(rootNode.right ? this.insertTree(rootNode.right, newTree) : rootNode.right = newTree);
}
}
let tree = new Trees();
for (let i = 20; i > 0; i -= 2) {
tree.insert(i - 1);
tree.insert(i);
}
console.log(tree);
结果: