function BinaryTree (){
var Node = function(key){
this.key = key;
this.left = null;
this.right = null;
};
var root = null;
var insertNode = function(node, newNode){
if (newNode.key < node.key) {
if (node.left === null) {
node.left = newNode;
}else {
insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
insertNode(node.right, newNode);
}
}
}
this.insert = function(key){
var newNode = new Node(key);
if (root === null) {
root = newNode;
} else {
insertNode(root, newNode);
}
}
}
var nodes = [8,3,56,1,9];
var binaryTree = new BinaryTree();
nodes.forEach(function(key){
binaryTree.insert(key);
});
var newNode = new Node(key); 运行时newNode = undifine;这是为什么?
木有返回值
Node属于类,必须用new影响实例化
谢谢啊,但我抄视屏里的,我仔细看过几遍这样写他没报错
Node对象在BinaryTree对象中,你这些写得不到,你想创建node对象,那就在BinaryTree对象的方法a中去new, 然后在外部通过binaryTree去访问自己的方法a,传key值就可以了。