Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Saturday, March 25, 2017

Tree: Preorder Traversal Hackerrank Java


/* you only have to complete the function given below.
Node is defined as

class Node {
    int data;
    Node left;
    Node right;
}

*/

void preOrder(Node root) {
    if(root instanceof Node)
        {
System.out.print(root.data+" ");
    preOrder(root.left);
    preOrder(root.right);
    }
}


EXPLANATION :


Here we are using instanceof to check whether root is valid entry or not 
After that a recursive call to the function so that it traverse in preorder

Reference

http://www.javatpoint.com/downcasting-with-instanceof-operator

0 Comments:

Post a Comment

Stats