[英]Javascript - Binary tree traversal in order. Last value is printing undefined
我正在打印出二叉樹中的所有節點,以便正確打印節點。 但是它還在列表的末尾打印了一個未定義的字符,我找不到原因。 我正在為編程競賽而學習,因此,如您所知,獲得完美的輸出非常重要。 只是控制台的事嗎? 我在控制台內置的VS Code和ubuntu終端中都嘗試過。 編碼:
function BST(value) {
this.value = value;
this.left = null;
this.right = null;
}
BST.prototype.insert = function(value) {
if( value <= this.value ){
if(this.left){
//left busy
this.left.insert(value);
}else{
//left is free
this.left = new BST(value);
}
}else{
if(this.right){
//right busy
this.right.insert(value);
}else{
//right is free
this.right = new BST(value);
}
}
}
BST.prototype.contains = function(value){
if(this.value === value){
return true;
}
if(value < this.value){
if(this.left){
return this.left.contains(value);
}else{
return false;
}
} else if(value > this.value){
if(this.right){
return this.right.contains(value);
}else{
return false;
}
}
}
BST.prototype.depthFirstTraversal = function(iteratorFunc){
if(this.left){
this.left.depthFirstTraversal(iteratorFunc);
}
if(this.value){
iteratorFunc(this.value);
}
if(this.right){
this.right.depthFirstTraversal(iteratorFunc);
}
}
var bst = new BST(50);
bst.insert(30);
bst.insert(70);
bst.insert(100);
bst.insert(60);
bst.insert(59);
bst.insert(20);
bst.insert(45);
bst.insert(35);
bst.insert(85);
bst.insert(105);
bst.insert(10);
console.log(bst.depthFirstTraversal(print));
function print(val){
console.log(val);
}
正在打印的列表是:
10
20
30
35
45
50
59
60
70
85
100
105
undefined
我為什么得到最后一個未定義的任何原因? 謝謝
您不需要記錄depthFirstTraversal
的結果,因為它不返回任何內容(或者,它返回undefined
)。 為了避免記錄該undefined
值,只需更改:
console.log(bst.depthFirstTraversal(print));
至
bst.depthFirstTraversal(print);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.