var Node = function (data, left, right) {
this.data = data;
this.left = left;
this.right = right;
};
Node.prototype.show = function () {
console.log("data:", this.data, "left:", this.left, "right:", this.right);
};
console.log("测试Node");
new Node(3, 1, 4).show();
var Tree = function () {
this.root = null;
};
Tree.prototype = {
constructor: Tree,
show: function () {
console.groupEnd(this.root);
},
insert: function (data) {
var node = new Node(data, null, null);
if (!this.root) {
this.root = node;
return;
}
let current = this.root;
while (current) {
if (data < current.data) {
if (!current.left) {
current.left = node;
break;
} else {
current = current.left;
}
} else {
if (!current.right) {
current.right = node;
break;
} else {
current = current.right;
}
}
}
},
getDeep() {},
getNode(data, root) {
if (root) {
if (data == root.data) {
return root;
} else if (data < root.data) {
return this.getNode(data, root.left);
} else {
return this.getNode(data, root.right);
}
} else {
return null;
}
},
getNodeFn(root) {
root = root || this.root;
return (data) => {
if (root) {
if (data == root.data) {
return root;
} else if (data < root.data) {
return this.getNode(data, root.left);
} else {
return this.getNode(data, root.right);
}
} else {
return null;
}
};
},
};
console.log("测试Tree");
var t = new Tree();
t.insert(7);
t.insert(2);
t.insert(5);
t.insert(1);
t.insert(3);
t.insert(4);
t.insert(6);
t.insert(8);
t.show();
console.log("getNode");
let fn = t.getNodeFn();
fn(3).show();