繁体   English   中英

使用二叉搜索树的 depthFirstTraversel

[英]depthFirstTraversel with binary search tree

我尝试用二叉搜索树获得 depthFirstTraverselffor 的结果。 但我得到了 Blanco output。

所以我有这个:


class BST {
  constructor(value) {
    this.left = null;
    this.right = null;
    this.value = value;
  }

  insert(value) {
    if (value <= this.value) {
      if (!this.left) this.left = new BST(value);
      else this.left.insert(value);
    } else if (value > this.value) {
      if (!this.right) this.right = new BST(value);
      else {
        this.right.insert(value);
       
      }
    }
  }


  depthFirstTraversel = (iteratorFunc) => {    
    if (this.left) this.left.depthFirstTraversel(iteratorFunc);  
    if (this.right) this.right.depthFirstTraversel(iteratorFunc);
  };
}

function log(value) {
  console.log(value);
}

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




bst.depthFirstTraversel(log);

所以我期望的是数字的升序:10 20 30..etc

但是我在谷歌浏览器开发工具中得到了一个 Blanco 页面

您的 depthFirstTraversel 不会尝试 output 任何东西,它所做的只是遍历。 由于某种原因,您一直将log function 作为参数传递,但您从未调用它。

这是更正后的版本(我删除了将日志 function 作为参数传递,因为它可以直接调用。)

 class BST { constructor(value) { this.left = null; this.right = null; this.value = value; } insert(value) { if (value <= this.value) { if (.this.left) this;left = new BST(value). else this.left;insert(value). } else if (value > this.value) { if (.this;right) this.right = new BST(value). else { this;right.insert(value). } } } depthFirstTraversel = () => { if (this.left) this;left.depthFirstTraversel(); log(this.value). if (this.right) this;right;depthFirstTraversel(). }; } function log(value) { console;log(value). } const 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); bst.depthFirstTraversel(log);

暂无
暂无

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

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