I have a binary search tree stated below:
4
/ \
2 6
/ \
1 3
I am looking to find an element, for example "3", and be able to get back an array of its path, which would be [3, 2, 4].
My issue is that when I return from the recursive function, I get back undefined. Additionally, when I console.log the path before it is returned, the console.log is correct but I do not get anything from the return.
Below is the code that I am trying to fix
let searchItem = (root, value, path) => {
const curr = root;
if(curr.val === value){
console.log(path)
return path;
}
if(curr.right){
searchItem(curr.right, value, [curr.right.val, ...path])
}
if(curr.left){
searchItem(curr.left, value, [curr.left.val, ...path])
}
}
let path1 = searchItem(root, 2, [root.val]);
console.log(path1)