Tree: Inorder Traversal Hackerrank problem solution

Tree: Inorder Traversal Hackerrank

In-order Traversal
In this traversal method, the left subtree is visited first, then the root and later the right sub-tree. We should always remember that every node may represent a subtree itself.
We start from A, and following in-order traversal, we move to its left subtree B. B is also traversed in-order. The process goes on until all the nodes are visited. The output of inorder traversal of this tree will be −

D → B → E → A → F → C → G

Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

If a binary tree is traversed in-order, the output will produce sorted key values in an ascending order.

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.

Output Format

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

Sample Input

Tree: Inorder Traversal Hackerrank

Sample Output

1 5 4 3 6 2

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

struct node
{
    int data;
    node* left;
    node* right;
};

*/

void inOrder(node *root) {
   if(root->left!=NULL)
        inOrder(root->left);
    cout<<root->data<<" ";
    if(root->right!=NULL)
        inOrder(root->right);
    
}

II

void Inorder(node *root) {
    if(root)
    {
        Inorder(root->left);
        cout << root->data << " ";
        Inorder(root->right);
    }
}

void inOrder(Node root) {
    if(root != null){
        inOrder(root.left);
        System.out.print(root.data + " ");
        inOrder(root.right);
    }
}
II Method

void Inorder(Node root) {
  if(root==null){
      return;
  }
    
    Inorder(root.left);
    System.out.print(root.data+" ");
    Inorder(root.right);
}


"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)
"""
import sys
def inOrder(root):
    #Write your code here
    if root != None:
        inOrder(root.left)
        sys.stdout.write(str(root.data))
        sys.stdout.write(" ")
        inOrder(root.right)

POst order tree
TREE preorder traversal click here

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

Leave a reply:

Your email address will not be published.