1

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!

2
  • For this example, you are correct. But to deep clone an object, assuming it has many levels, the JSON method is pretty simple and perhaps quickest. Regarding walking through my code, why do you assume that I hadn't? I console.logged every step of the way and had no idea why in the function, 'path' held the correct value, but after the 'return path' it was undefined. I walked through each line. Commented Jul 20, 2015 at 11:14
  • Why the down-vote/close vote? Commented Jul 21, 2015 at 18:34

1 Answer 1

8

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.