1

I was wanting to display all of the nodes at a certain level in the tree:

Called by: allNodesAtACertainLevel(0, *whatever level you want*, root);

This produces the correct answer.

private void allNodesAtACertainLevel(int count, int level, Node n){

        count += 1;

        if(count <= level){
            if(n.left != null) allNodesAtACertainLevel(count, level, n.left);
            if(n.right != null) allNodesAtACertainLevel(count, level, n.right);
        }
        else{
            System.out.print(n.value);
        }

    }

This doesn't.

private void allNodesAtACertainLevel(int count, int level, Node n){

        if(count < level){
            if(n.left != null) allNodesAtACertainLevel(count++, level, n.left);
            if(n.right != null) allNodesAtACertainLevel(count++, level, n.right);
        }
        else{
            System.out.print(n.value);
        }

    }

Could someone explain why?

2 Answers 2

6

The second example increments count twice, the first example increments count only once. Also the first increments count before calls to allNodesAtACertainLevel while second example calls allNodesAtACertainLevel and increments count after the call.

Any of these should produce a correct result when substituted appropriately for the second example:

count++;
if(n.left != null) allNodesAtACertainLevel(count, level, n.left);
if(n.right != null) allNodesAtACertainLevel(count, level, n.right);

--

count += 1;
if(n.left != null) allNodesAtACertainLevel(count, level, n.left);
if(n.right != null) allNodesAtACertainLevel(count, level, n.right);

--

if(n.left != null) allNodesAtACertainLevel(count+1, level, n.left);
if(n.right != null) allNodesAtACertainLevel(count+1, level, n.right);
Sign up to request clarification or add additional context in comments.

3 Comments

I thought it would only increment the value within the scope of the respective recursive call.
@Ryan: It increments it within the scope of the variable, not in the call. I've added some equivalent versions, the last is likely what you were really going for.
You're correct, the last example is what I thought would be happening. Thank you for the explanation!
2

Your problem is because you are making count++ to times, so you increment the level counter one extra time.

You should change your code to the following:

count++;
if(n.left != null) allNodesAtACertainLevel(count, level, n.left);
if(n.right != null) allNodesAtACertainLevel(count, level, n.right);

2 Comments

Wouldn't this return an incorrect answer if the left node were ever null and the right node wasn't?
You are right, i have missed the one-liner if statement, corrected now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.