gpt4 book ai didi

javascript - 在 JavaScript 中查找节点的高度

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

在我的 JavaScript 代码中,我试图在二叉搜索树中查找给定节点的高度。这是我的代码

class BinarySearchTree2 {
constructor() {
this.root = null;
}

findHeight(node = this.root,nodeData,level = 1) {
let root = node;
if(root === null)
return null;
if(root.data === nodeData)
return level;
let foundLevel = 0;
if(nodeData < root.data) {
foundLevel = findHeight(root.left,nodeData,level + 1);
}
// If you have found it on the left subtree, that's it, return
if(foundLevel !== 0)
return foundLevel;
foundLevel = findHeight(root.left,nodeData,level + 1);
return foundLevel;

}
}

现在,当我插入一些节点并尝试查找节点的高度时,例如:

let BST = new BinarySearchTree2();

BST.insert(8);
BST.insert(3);
BST.insert(10);
BST.insert(1);
BST.insert(6);
BST.insert(14);
BST.insert(4);
BST.insert(7);
BST.insert(13);

BST.findHeight(this.root,14,1);

它抛出错误。说 findHeight 未定义。

我做错了什么?

最佳答案

如果您想调用其内部的方法,您仍然需要使用 this 因为您尝试调用的方法实际上附加到对象本身。所以,

class BinarySearchTree2 {
constructor() {
this.root = null;
}

findHeight(node = this.root,nodeData,level = 1) {
let root = node;
if(root === null)
return null;
if(root.data === nodeData)
return level;
let foundLevel = 0;
if(nodeData < root.data) {
// change here
foundLevel = this.findHeight(root.left,nodeData,level + 1);
}
// If you have found it on the left subtree, that's it, return
if(foundLevel !== 0)
return foundLevel;
// change here
foundLevel = this.findHeight(root.left,nodeData,level + 1);
return foundLevel;

}
}

将按预期工作

关于javascript - 在 JavaScript 中查找节点的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53833688/

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