January 26, 2019

Do inorder traversal on a binary tree in java.

Hello there.

In this article, we will be traversing a binary tree, and we also print the data stored in those node.

In the inorder traversal, we print the left child rootright child.

Here is simple recursive algorithm to do that.

  1. go to left child – print the left child
  2. print the root
  3. go to right child – print the right child

Recursion can be a little difficult to understand. But, that’s ok, no one understands that in the beginning.

And, we also have to add a termination case to end the recursion. Because, we do not want to blow out the stack

The recursion terminator.

if (head == null) return ;

Inorder Traversal :-

//print head between left and right childs
    public static void inorder(BinaryTreeNode head) {
    if (head == null) return ;
    
    inorder(head.left);
    System.out.println(head.name);
    inorder(head.right);
}

Let us write a test code to use the above function.

public class BinaryTreeTraversal {

    public static void main(String  ... args) {
        BinaryTreeNode head = CreateBinaryTree.createCompleteBinaryTree('A', 'B', 'Z', 'E', 'P', 'Q');
    
        System.out.println("--InOrder--");
        inorder(head);
    }

}

We are using BinaryTreeNode as a node for binary tree and we are using utility function -which creates a binary tree is defined in this article – here.

The output of above code.

--InOrder--
E
B
P
A
Q
Z

So, we just traversed the binary tree in inorder.

thanks for reading.. bye for now.. 🙂

Tagged on: