简体   繁体   English

Javascript-按顺序遍历二叉树。 上一个值正在打印未定义

[英]Javascript - Binary tree traversal in order. Last value is printing undefined

I'm printing out all the nodes in a binary tree in order which is printing the nodes correctly. 我正在打印出二叉树中的所有节点,以便正确打印节点。 But it's also printing an undefined at the end of the list and I can't find the reason why. 但是它还在列表的末尾打印了一个未定义的字符,我找不到原因。 I'm studying for a programming contest and It's important to get a perfect output as you already know. 我正在为编程竞赛而学习,因此,如您所知,获得完美的输出非常重要。 Is it just a console thing? 只是控制台的事吗? I tried it both in VS Code built in console and in the ubuntu terminal. 我在控制台内置的VS Code和ubuntu终端中都尝试过。 The code: 编码:

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);
 }

The list being printed is: 正在打印的列表是:

10
20
30
35
45
50
59
60
70
85
100
105
undefined

Any reason why I'm getting that last undefined?. 我为什么得到最后一个未定义的任何原因? Thanks 谢谢

You don't need to log the result of depthFirstTraversal because it doesn't return anything (or rather, it returns undefined ). 您不需要记录depthFirstTraversal的结果,因为它不返回任何内容(或者,它返回undefined )。 To avoid logging that undefined value just change: 为了避免记录该undefined值,只需更改:

console.log(bst.depthFirstTraversal(print));

to

bst.depthFirstTraversal(print);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM