gpt4 book ai didi

javascript - 为什么当我遍历树时超出了调用堆栈的最大大小?

转载 作者:太空宇宙 更新时间:2023-11-04 15:30:27 25 4
gpt4 key购买 nike

我试图从二叉树中获取最小值,但收到错误消息,指出超出了最大调用堆栈大小。如何正确获取二叉搜索树中项目的最小值?

这是我的代码 JSBin :

function Node(val){
this.value = val;
this.left = null;
this.right = null;
}

function BinarySearchTree(){
this.root = null;
}
BinarySearchTree.prototype.minNode =function() {
var node = this.root;
if(!node){
return 0;
}
if(node.left){
return this.minNode(node.left)
}
return node.value
}

BinarySearchTree.prototype.push = function(val){
var root = this.root;

if(!root){
this.root = new Node(val);
return;
}

var currentNode = root;
var newNode = new Node(val);

while(currentNode){
if(val < currentNode.value){
if(!currentNode.left){
currentNode.left = newNode;
break;
}
else{
currentNode = currentNode.left;
}
}
else{
if(!currentNode.right){
currentNode.right = newNode;
break;
}
else{
currentNode = currentNode.right;
}
}
}

}

var bt = new BinarySearchTree();
bt.push(23);
bt.push(1);
bt.push(2);
bt.push(25);
console.log(bt.minNode());

最佳答案

就像@AndrewLi提到的。您通过编写再次设置相同的根

var node = this.root;

改为更改函数的定义

BinarySearchTree.prototype.minNode =function(nextNode) {
var node = nextNode || this.root;
if(!node){
return 0;
}
if(node.left){
return this.minNode(node.left)
}
return node.value
}

关于javascript - 为什么当我遍历树时超出了调用堆栈的最大大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44831037/

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