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?