【问题标题】:Javascript - Binary tree traversal in order. Last value is printing undefinedJavascript - 按顺序遍历二叉树。最后一个值是打印未定义
【发布时间】:2019-01-12 05:04:19
【问题描述】:

我正在按正确打印节点的顺序打印出二叉树中的所有节点。但它也在列表末尾打印一个未定义的,我找不到原因。我正在为一场编程比赛而学习,如你所知,获得完美的输出很重要。它只是一个控制台的东西吗?我在控制台内置的 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

我得到最后一个未定义的任何原因?谢谢

【问题讨论】:

  • 您的代码中似乎还有一个错误,您的树找不到 0。if (this.value)
  • 我已经删除了该部分,因为它不是必需的,并对其进行了重构以支持预购、中购和后购。感谢您让我知道这个错误!

标签: javascript algorithm binary-tree


【解决方案1】:

您不需要记录depthFirstTraversal 的结果,因为它不返回任何内容(或者更确切地说,它返回undefined)。为避免记录 undefined 值,只需更改:

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

bst.depthFirstTraversal(print);

【讨论】:

  • 我很惭愧地说我没有发现这一点。或许您可以为未来的读者了解为什么会发生这种情况。
  • 大声笑。我不敢相信我错过了。我已经编码了 12 个小时,该睡觉了哈哈。将在几分钟内接受您的回答。谢谢
  • 是的@Juan 有时候用新鲜的眼睛会更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-07
  • 2018-12-01
  • 2020-08-18
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多