2

I am studying binary trees. I saw online a code to traverse the entire binary tree. Here's the code I got: '''

public void showAll(Node node)
{
    Node parent = node;
    if(parent != null)
    {
        System.out.println(" " + parent.person);
        showAll(parent.leftChild);
        showAll(parent.rightChild);
    }
}

'''

What I dont understand is how this function can print the right child? According to code everytime the function is called left child is printed. The code never reaches the right child.

2 Answers2

0

This is a textbook implementation of postorder traversal. Also known by some as "bottom up" traversal.

Postorder traversal

For each iteration the leftmost node then the rightmost node is printed. If the parent node is ever null then the tree is past the highest node, i.e. the algorithm has finished.

NotZack
  • 518
  • 2
  • 9
  • 22
-2

Try to dry run the code with binary tree having, say 5 nodes. And then you'll probably figure it out. Even then if you are facing problems, learn a little about how a compiler calls functions or what actually stacktrace is.