gpt4 book ai didi

javascript - 类型错误:无法读取未定义的属性 'data' - 但已定义

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:48 25 4
gpt4 key购买 nike

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

代码如下:

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.leftundefined 而你应该做 parentNode.leftNode

关于javascript - 类型错误:无法读取未定义的属性 'data' - 但已定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52459854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com