gpt4 book ai didi

JavaScript:如何实现二叉搜索树

转载 作者:行者123 更新时间:2023-12-04 15:25:18 26 4
gpt4 key购买 nike

我正在 JavaScript 中实现二叉搜索树,但是在编写插入函数时,发生了一些错误(很可能在 RECURSION 中)。

这是我的代码:

class BinarySearchTree {
constructor() {
this.length = 0;
this.root = null;
}
insert(elem) {
if (!this.root) {
//If root is null then this is the root.
this.root = new BSTNode(elem);
} else {
let newNode = new BSTNode(elem);
let myRoot = this.getParent(this.root, elem)
console.log(myRoot);

if (myRoot[1] == 'left') myRoot[0].left = newNode; //Error Line
else myRoot[0].right = newNode;

this.nodes.push(newNode);
this.arr.push(elem);
}
this.length++
}
getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

if (elem < root.value) {
if (root.left!==null) this.getParent(root.left, elem);
else return [root, 'left'];
} else {
if (root.right!==null) this.getParent(root.right, elem);
else return [root, 'right']
}
}
}
class BSTNode {
constructor(val) {
this.value = val;
this.left = null; //Left Node
this.right = null; //Right Node
}
}

有两个类;即 BinarySearchTreeBSTNode .

错误: Uncaught TypeError: Cannot read property '1' of undefined
我无法找到错误。

请注意,也欢迎使用其他解决方案来做同样的事情。

最佳答案

你应该返回 this.getParent(root.left, elem); 的结果和 this.getParent(root.right, elem);

getParent(root, elem) { // the argument 'root' is ambiguous, but it is for the user

if (elem < root.value) {

if (root.left!==null) return this.getParent(root.left, elem);
else return [root, 'left'];
} else {
if (root.right!==null) return this.getParent(root.right, elem);
else return [root, 'right']
}
}

关于JavaScript:如何实现二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62375423/

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