二叉树创建
function BinaryTree() {
this.root = null;
this.insert = function (key) {
var node = new BinaryNode(key);
if (this.root) {
this._insertNode(node, this.root);
} else {
this.root = new BinaryNode(key);
}
}
this._insertNode = function (node, tree) {
if (node.key < tree.key) {
if (tree.left) {
this._insertNode(node, tree.left);
} else {
tree.left = node;
}
} else {
if (tree.right) {
this._insertNode(node, tree.right);
} else {
tree.right = node;
}
}
}
function BinaryNode(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
var arr = [8, 13, 14, 6, 7, 3, 1];
var binaryTree = new BinaryTree();
arr.forEach(item => {
binaryTree.insert(item);
});
console.log(binaryTree.root);