3
public static void preorder(Node root) {
    if(root == null) return;

    root.printValue();
    preorder(root.getLeft());
    preorder(root.getRight());
}

I have tried to go through this function numerous times but i still can't figure out how after traversing through all the left children the algorithm goes back to the nearest ancestor(parent). Could someone explain this to me.

cantfindaname88
  • 195
  • 1
  • 6
  • 15
  • 2
    The way to learn is to get out a piece of paper, draw a simple tree with a few elements, and run the algorithm STEP BY STEP – Kon Sep 13 '13 at 05:05
  • 1
    Using a piece of paper really helped me get to the conclusion of this. My first approach was to use stack implementation. Then I stepped through the recursion calls and realized they also behave like stacks. Thanks guys. – cantfindaname88 Sep 13 '13 at 06:33

2 Answers2

8

There's an implicit return at the end of your void method:

public static void preorder(Node root) {
    if(root == null) return;

    root.printValue();
    preorder(root.getLeft());
    preorder(root.getRight());
    return;
}

You always return to the method that called you. So, if the parent's method call makes another call for the child, then when the child's method call returns, it returns to the parent's. Right?

Hope that makes sense. Like Kon said, you should just run through the algorithm on paper. Or, better yet, if you know how to use a debugger, you can just step through your code in the debugger and see how it works.

DaoWen
  • 32,589
  • 6
  • 74
  • 101
2

When traversal reaches leaf node, it's left and right children will be NULL. And preorder(root.getLeft()) will pass NULL and will return. Same way the right will also return NULL. Then the stack pops and goes back to parent.

I think it would be best if you can dry-run this using a stack then you'll be able to better understand it.

gusaki
  • 741
  • 7
  • 13