Tree: Preorder Traversal Hackerrank Solution

Complete the preOrder 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 preorder 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 preOrder function.

Constraints

1 <=  Nodes in the tree <= 500 

Output Format

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

Sample Input

     1
      \
       2
        \
         5
        /  \
       3    6
        \
         4  

Sample Output

1 2 5 3 4 6 

Iterative apporach:

 public static void preOrder(Node root) {
        Stack<Node> s = new Stack<>();

        s.push(root);
        while(!s.isEmpty()) {
            Node curr = s.peek();
            System.out.print(curr.data + " ");
            s.pop();

            if(curr.right != null)
            s.push(curr.right);
            if(curr.left != null)
            s.push(curr.left);
        }

    }

Recursive apporach:

 public static void preOrder(Node root) {

        if(root == null)
        return;
        System.out.print(root.data + " ");
        preOrder(root.left);
        preOrder(root.right);

    }

Hope you all get the concept of preorder traversal using both iterative and recursive approach.

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: