首页 > 解决方案 > TypeError:无法读取未定义的属性“数据”-但已定义

问题描述

我正在研究二叉搜索树算法,由于某种原因,我不断收到类型错误。它总是在将第二个值插入树时发生。特别是当当前节点的值与传入的数据值进行比较时

这是代码:

class Node {
    constructor(data, left = null, right = null) {
        this.data = data;
        this.leftNode = left;
        this.rightNode = right;
    }
}

class BST {
    constructor() {
        this.root = null;
    }
    insert(data) {
        const dataNode = new Node(data);
        if (this.root === null) {
            this.root = dataNode;
        } else {
            let currentNode = this.root;
            let parentNode;
            while (true) {
                parentNode = currentNode;
                if (data < currentNode.data) {
                    currentNode = parentNode.left;
                    if (parentNode.left === null) {
                        parentNode.left = dataNode
                        break;
                    }
                } else {
                    currentNode = parentNode.right
                    if (parentNode.right === null) {
                        parentNode.right = dataNode
                        break;
                    }
                }
            }
        }
    }
}
const bst = new BST();

bst.insert(10);
bst.insert(5);
bst.insert(6);
bst.insert(8);
bst.insert(12);
bst.insert(7);
bst.insert(7);

这是错误:

Uncaught TypeError: Cannot read property 'data' of undefined
    at BST.insert (<anonymous>:22:32)
    at <anonymous>:42:5

标签: javascriptbinary-search-treetypeerrorgraph-algorithm

解决方案


你正在做parentNode.left的是undefined你应该做的parentNode.leftNode


推荐阅读