Javascript递归函数返回undefined

Javascript recursion function returning undefined

本文关键字:undefined 返回 递归函数 Javascript      更新时间:2023-09-26

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

我正在写一个函数,简单地循环通过二叉树。假设我们有一个简单的树,如:

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

我们正试图从它收集数据,从最左边的路径开始。下面是左侧搜索函数:

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,[]));

我得到

定义

为什么函数不能正确返回[10]?

谢谢!

递归调用必须将值返回给调用者

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
}