Als*_*eio 3 javascript typeerror graph-algorithm binary-search-tree
我正在研究二叉搜索树算法,由于某种原因,我不断收到类型错误.当第二个值插入树中时,总会发生这种情况.特别是当当前节点的值与传入数据值进行比较时
这是代码:
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);Run Code Online (Sandbox Code Playgroud)
这是错误:
Uncaught TypeError: Cannot read property 'data' of undefined
at BST.insert (<anonymous>:22:32)
at <anonymous>:42:5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
846 次 |
| 最近记录: |