问答详情
源自:1-4 二叉树创建的代码实现

Cannot read property 'key' of null

function Bin() {

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.key === 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, 10, 1, 14, 7, 13];

var bin = new Bin();

nodes.forEach(function (key) {

bin.insert(key);

});


提问者:慕课_小菜鸟 2018-08-26 15:43

个回答

  • 慕先生51210
    2019-06-09 12:07:26

    function Bin() {

    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.key === null) {                //此处node.key改为node.left

    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, 10, 1, 14, 7, 13];

    var bin = new Bin();

    nodes.forEach(function (key) {

    bin.insert(key);

    });



  • qq_miracle猫蝶_0
    2018-09-09 17:12:00

    var insertNode = function(node,newNode){/*外部不可调用的插入操作*/

    if(node.key>newNode.key)

    {

    if(node.leftChild===null)

    {

    node.leftChild = newNode;

    }else{

    insertNode(node.leftChild,newNode)

    }

    }else{

    if(node.rightChild===null)

    {

    node.rightChild = newNode;

    }else{

    insertNode(node.rightChild,newNode)

    }

    }

    };

    你是不是打错了··