简体   繁体   中英

depthFirstTraversel with binary search tree

I try to get the results of depthFirstTraverselfor with binary search tree. But I get a Blanco output.

So I have this:


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

So what I expect is a ascending order of the numbers: 10 20 30..etc

But I get a Blanco page back in google chrome dev tools

Your depthFirstTraversel doesn't try to output anything, all it does is traverse. You keep passing the log function as a parameter, for some reason, but you never call it.

Here's a corrected version (I removed passing the log function as parameter, because it can just be called directly.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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