TypeError: Cannot read property 'data' of undefined - but it is defined

TypeError: Cannot read property 'data' of undefined - but it is defined

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

代码如下:

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

你正在做 parentNode.left,这是 undefined 而你应该做 parentNode.leftNode

你打错了。固定片段如下:

class Node {
  constructor(data, left = null, right = null) {
    this.data = data;
    this.left = left;
    this.right = 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);

您似乎在为 parentNode.left 赋值之前将 parent.left 赋给了 currentNode 这也发生在右边。