Tree: Postorder Traversal Hackerrank problem solution

Tree: Postorder Traversal Hackerrank

In a postorder traversal, we recursively do a postorder traversal of the left subtree and the right subtree followed by a visit to the root node.
When trying to figure out what the algorithm for this problem should be, you should take a close look at the way the nodes are traversed – there is a pattern in the way that the nodes are traversed.

If you break the problem down into subtrees you can see that these are the operations that are being performed recursively at each node:

1. Traverse the left subtree

2. Traverse the right subtree

3. Visit the root

This sounds simple enough. Let’s now start writing some actual code
Complete the postOrder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree’s postorder 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 postOrder function.

Output Format

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

Sample Input

Tree: Postorder Traversal Hackerrank

Sample Output

1 4 5 6 2 3

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

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


void postOrder(node *root) {
    cout<<root->data<<" ";
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node) (the value of the node)
import sys
def postOrder(root):
    #Write your code here
    if root != None:
        sys.stdout.write(" ")
I Method

void postOrder(Node root) {
    if(root != null){
        System.out.print( + " ");

void Postorder(Node root) {
    if (root == null) { return; }
    System.out.print( + " ");

TREE preorder traversal click here

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

Leave a reply:

Your email address will not be published.