我想從我的二叉樹得到最小值,但我得到一個錯誤,最大調用堆棧大小已超出。如何正確獲取二叉搜索樹中項目的最小值?爲什麼我遍歷樹時超出了調用堆棧的最大尺寸?
這裏是我的代碼在:
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());
你不會推進'節點'。您在每次遞歸中將其設置爲根。 – Li357
它不是最新的嗎?什麼是正確的方式.t獲得最小值 – user5711656
您或者需要將它作爲參數傳遞給遞歸方法,或者您需要在實例上保留一個'.currentSearchNode'屬性並使用它來代替'this.root'你可以跟蹤你在哪裏。請注意,這對於任何有意義的數據集都可以很容易地溢出堆棧。 JavaScript在處理直接遞歸方面並不太好。相反,你總是可以蹦蹦跳跳。 –