JavaScript 种一颗二叉树
/* 实现一颗树 结点类:Tree 包含左子树left,右子树right,根节点root,缺省为null 构造设置value 树类:Trees 构造:默认根节点为null
insert: 如果当前根节点不存在,则将传进来的节点存为根节点 如果当前根节点存在,执行InsertTree
insertTree(rootNode,newTree): 1 如果新树value小于根节点value,放到根节点的左边,如果根节点左子树已经存在,以根节点左子树为根节点继续递归 2 如果新树value大于等于根节点value,放到根节点右边,如果根节点右子树已经存在,以根节点右子树为根节点继续递归 */
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);