Tree: Inorder Traversal Hackerrank Solution

Complete the inOrder function in your editor below, which has parameter: a pointer to the root of a binary tree. It must print the values in the tree’s inorder traversal as a single line of space-separated values.

Input Format

Our hidden tester code passes the root node of a binary tree to your inOrder function.

Constraints

1 Nodes in the tree  500

Output Format

Print the tree’s inorder traversal as a single line of space-separated values.

Sample Input

     1
      \
       2
        \
         5
        /  \
       3    6
        \
         4  

Sample Output

1 2 3 4 5 6 

Code:

 public static void inOrder(Node root) {
        if(root == null)
        return;
        Stack<Node> stack = new Stack<>();
        Node current = root;
        while(current != null || !stack.isEmpty()) {
           

            while(current != null) {
                stack.push(current);
                current = current.left;
            }
            current = stack.pop();
            System.out.print(current.data + " ");
            current = current.right;
        }


    }

Code Using Recursion:

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

        inOrder(root.left);
        System.out.print(root.data + " ");
        inOrder(root.right);

    }

Hope you all get the concept of inorder traversal using both iterative and recursive approch.

To learn recursion and tree traversal in details .

In the next blog we will see other tree traversal implementation using both methods i.e iterative and recursive in java.

So till then Bye Bye…!

Happy Coding..!

Thank You…!



Categories: HackerRank Questions

Tags: , , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: