繁体   English   中英

二叉搜索树递归返回未定义 - Javascript

[英]Binary Search Tree Recursion returning undefined - Javascript

我有一个二叉搜索树,如下所示:

      4
    /   \
  2      6
 / \    
1   3  

我正在寻找一个元素,例如“3”,并且能够取回它的路径数组,这将是 [3, 2, 4]。

我的问题是,当我从递归函数返回时,我返回未定义。 此外,当我在返回之前 console.log 路径时,console.log 是正确的,但我没有从返回中得到任何东西。

下面是我试图修复的代码

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)

您需要检查该值并返回走分支的结果。

 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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM