0

I'm trying to understand recursion better in Javascript with this code for a BST. I can print out a BST's values with two methods using recursion, but I can't figure out how to do it all in one method.

how can I combine

BinarySearchTree.prototype.dfs = function(node) {
  if (node) {
    console.log(node.val);
    this.dfs(node.left);
    this.dfs(node.right);
  }
}

BinarySearchTree.prototype.depthFirstTraversal = function() {
  let current = this.root;
  this.dfs(current);
}

into one function? I've been trying

BinarySearchTree.prototype.sameFunction = function(node = null) {
    // if node is null use this.root
    let current = node || this.root;
 
    if (current) {
        console.log(current.val);
        this.sameFunction(current.left);
        this.sameFunction(current.right);
    }
}

http://jsfiddle.net/rj2tyd4L/

2
  • Why? Two methods are much better here than one, because there's a clear separation of concerns: the main method applies to the whole tree, the helper method - to a particular node. Commented Oct 25, 2018 at 18:16
  • I agree. But as a more general question to learn recursion. Commented Oct 25, 2018 at 18:35

1 Answer 1

1

What about using a second argument isRoot with it's default value set to true?

BinarySearchTree.prototype.sameFunction = function(node = null, isRoot = true) {
  let current = isRoot ? this.root : node;
  if (current) {
    console.log(current.val);
    this.sameFunction(current.left, false);
    this.sameFunction(current.right, false);
  }
}

http://jsfiddle.net/fez1jtsx/

This makes tree.sameFunction() equivalent to calling tree.depthFirstTraversal()

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. any idea why this doesn't work when I make it a class method? jsfiddle.net/n8ea7ou2
@totalnoob you missed the if statement: if (current) {...}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.