3

I am trying to traverse through a binary search tree using in order traversal and the recursion method. My goal is to push each node's value into an array and return it. Here is my code:

  dfsInOrder(node=this.root) {
    let nodes = []
    if(node === null) return 


    nodes.push(this.dfsInOrder(node.left))
    nodes.push(node.val)
    nodes.push(this.dfsInOrder(node.right))
    return nodes
  }

Here is how I am inserting the data into the tree:

binarySearchTree
  .insert(15)
  .insert(20)
  .insert(10)
  .insert(12);

For clarification the root of the tree's value is 15 and both 10 and 12 are on the left side of the tree. 20 is on the right.

I am looking for a result like this:

[12,10,15,20]

But instead I am getting this:

[Array(3), 15, Array(3)].....


[undefined, 10, Array(3)]
15
[undefined, 20, undefined]

Where am I going wrong in my code?

1 Answer 1

2

Here's one way to fix this:

dfsInOrder(node=this.root) {
  const nodes = [];

  if (node !== null) {
    nodes.push(
      ...this.dfsInOrder(node.left),
      node.val,
      ...this.dfsInOrder(node.right)
    );
  }

  return nodes;
}

In this code, dfsInOrder...

  • always returns a flat array, empty for edges. This is slightly better from type check perspective, but also allows filtering out these undefined values you see now
  • always flattens results of recursive calls (by ... operator) when inserting them to the resulting array

As a sidenote, push doesn't change your array reference, so there's no need to use let here. Actually, this function can be rewritten to avoid intermediate variable completely:

dfsInOrder(node=this.root) {
  if (node === null) return [];

  return [
    ...this.dfsInOrder(node.left),
    node.val,
    ...this.dfsInOrder(node.right),
  ];
}

... which is fine by me, but is slightly harder to debug.

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

2 Comments

For some reason I get an error saying this.dfsInOrder is not an iterable when I use the spread operator
Are you sure you didn't leave those empty return statements?

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.