问题
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