繁体   English   中英

Javascript递归函数返回未定义

[英]Javascript recursion function returning undefined

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

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

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(path) 显示正确的值:

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

暂无
暂无

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

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