Javascript recursion function returning undefined

大城市里の小女人 提交于 2020-01-14 04:32:06

问题


I'm not even certain what the title of this question should be - I'm not sure what is going wrong at all.

I'm writing a function that simply loops through a binary tree. Let us say we have a simple tree such as:

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

We're trying to collect the data from it, starting with going the left-most path. Here is the search left function:

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

When I run it, the inner console.log(path) shows the correct value:

[10]

But if I

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

I get

undefined

Why isn't the function properly returning [10]?

Thank you!


回答1:


Your recursive call have to return the value to the caller

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
}


来源:https://stackoverflow.com/questions/31508709/javascript-recursion-function-returning-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!