Javascript 返回未定义的递归函数

Javascript recursion function returning undefined

我什至不确定这个问题的标题应该是什么 - 我完全不确定出了什么问题。

我正在编写一个简单地循环遍历二叉树的函数。假设我们有一棵简单的树,例如:

testTree = { 
  data: 5,
  left: { 
    data: 10, 
    left: undefined, 
    right: undefined 
  },
  right: { 
    data: 2, 
    left: undefined, 
    right: undefined 
  } 
}

我们正在尝试从中收集数据,从 left-most 路径开始。这是搜索左侧功能:

function searchLeft(node, path){
  if(typeof node.left == 'undefined'){
    console.log(path);
    return path;
  }
  node = JSON.parse(JSON.stringify(node.left));
  path.push(node.data);
  searchLeft(node,path);
}

当我运行它时,内部console.log(路径)显示正确的值:

[10]

但是如果我

console.log(searchLeft(testTree,[]));

我明白了

undefined

为什么函数没有正确返回 [10]?

谢谢!

你的递归调用必须return调用者的值

function searchLeft(node, path) {
    if (typeof node.left == 'undefined') {
        console.log(path);
        return path;
    }
    node = JSON.parse(JSON.stringify(node.left));
    path.push(node.data);
    return searchLeft(node, path); //here return
}