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)
You need to check the value and return the result of walking the branch.
let searchItem = (node, value, [...path] = []) => { if (!node) return; path.unshift(node.val); if (node.val === value) return path; return searchItem(node.left, value, path) || searchItem(node.right, value, path); }, tree = { val: 4, left: { val: 2, left: { val: 1 }, right: { val: 3 } }, right: { val: 6 } }; console.log(searchItem(tree, 2)); console.log(searchItem(tree, 3)); console.log(searchItem(tree, 6));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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.