Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Postorder Traversal

Easy
0/40
Average time to solve is 15m
profile
Contributed by
50 upvotes
Asked in companies
AmazonMicrosoftPayPal

Problem statement

You have been given a Binary Tree of 'n' nodes, where the nodes have integer values. Your task is to return its postorder traversal.


For Example:
For the given tree below,
Postorder traversal for the given tree will be [4, 5, 2, 3, 1]. Hence, the answer is [4, 5, 2, 3, 1].

Example

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains the elements of the tree in the level order form separated by a single space. If any node does not have a left or right child, take -1 in its place. Refer to the example for further clarification.
Example:
Elements are in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 in its place.

For example, the input for the tree depicted in the below image would be :

Example

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :
Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. 

The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

The input ends when all nodes at the last level are null (-1).
Output Format:
The output contains single line of 'n' space-separated integers denoting the post-order traversal of the given binary tree.
Note:
You do not need to print anything. It has already been taken care of. Just implement the function.
Sample Input 1:
1 2 3 4 -1 -1 5 6 7 -1 -1 -1 -1 -1 -1
Sample Output 1:
6 7 4 2 5 3 1
Explanation:
The given tree is:

binaryTree

Postorder traversal for the given tree will be [6, 7, 4, 2, 5, 3, 1]. Hence, the answer is [6, 7, 4, 2, 5, 3, 1].
Sample Input 2:
10 20 11 -1 -1 -1 -1
Sample Output 2:
20 11 10
Expected time complexity:
The expected time complexity is O(n).
Constraints :
1 <= 'n' <= 10^5
0 <= 'data' <= 10^5     

where 'n' is the number of nodes and 'data' denotes the node value of the binary tree nodes.

Time limit: 1 sec
Hint

Try to use a recursive approach.

Approaches (2)
Recursion

In this approach, we will create a recursive function postorder(node, ans) that will traverse all the nodes and store the postorder traversal in an array ans. We will first recursively call this function for its left and right subtree to traverse the nodes in the left and right subtree, and then insert the node’s value into ans array for each node.

 

Algorithm:

  • Defining the postorder(node, ans)
    • If the node is an empty node, we will return from the function.
    • Now we will traverse to the left subtree.
    • Create a recursive call postorder(left child of the node, ans).
    • Now we will traverse to the right subtree.
    • Create a recursive call postorder(right child of the node, ans).
    • Insert node value into the ans array
  • We will define an array ans to store the postorder traversal of the given tree.
  • We will call postorder(root, ans).
  • Return the array ans.
Time Complexity

O(N), where N is the number of nodes in the tree.

 

In this approach, we traverse each node once, and there are N nodes in the tree. Hence, the overall time complexity is O(N).

Space Complexity

O(N), where N is the number of nodes in the tree.
 

We use O(N) space complexity for recursive stack during recursion calls in the worst case. The space complexity O(N) is also used for storing the postorder traversal. Hence, the overall space complexity is O(N).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Postorder Traversal
All tags
Sort by
Search icon

Interview problems

Postorder Traversal Easy CPP Solution 100%

void post(TreeNode *root , vector<int> & ans){

    if(root == NULL) return ;

    post(root->left, ans);

    post(root->right, ans);

    ans.push_back(root->data);

}

vector<int> postorderTraversal(TreeNode *root)

{

    // Write your code here.

    vector<int> ans ;

    post(root , ans );

    return ans ;

}

29 views
0 replies
0 upvotes

Interview problems

C++||Easy Solution||Pre Order Traversal||Recursive Approach||✅✅

void postOder(TreeNode * root, vector<int>&v)

{

    if(root==NULL)

    {

        return;

    }

    postOder(root->left, v);

    postOder(root->right, v);

    v.push_back(root->data);

 

}

vector<int> postorderTraversal(TreeNode *root)

{

    // Write your code here.

    vector<int>v;

    postOder(root, v);

    return v;

    

}

211 views
0 replies
0 upvotes

Interview problems

Iterative PostOrder Traversal of binary tree. Using 1 Stack in C++

// ------------------ postOrder using 1 stack -------------------------
 vector<int> postorderTraversal(TreeNode *root){
     vector<int>ans;
     if(root == nullptr) return ans;
    stack<TreeNode*>s;

     while(root!=nullptr || !s.empty() )
     {
         if(root!= nullptr)
         {
             s.push(root);
             root = root->left;
         }
         else{
         TreeNode* temp = s.top()->right;

         if(temp == nullptr){
             //TreeNode* temp = s.top();
             temp = s.top();
             s.pop();
             ans.push_back(temp->data);
             while(!s.empty() && s.top()->right == temp){
                 temp = s.top();
                 s.pop();
                 ans.push_back(temp->data);

             }
         }
         else
         root = temp;
         }
     }
     return ans;
 }

beginners

tutorial

100daysofcode

datastructures

+1 more
125 views
0 replies
0 upvotes

Interview problems

postOrder using two stacks in C++ Unique Approach. Striver sheet but not stiver solution.

https://github.com/yashswag22/Striver-A-to-Z-DSA-sheet < = all dsa sheet solution available for beginners.

 // -------------------- postOrder using two stacks --------------------

 vector<int> postorderTraversal(TreeNode *root){
     stack<TreeNode*>s;
     stack<bool>chacki;
    vector<int>ans;
    if(root == nullptr)  return ans;

    while(root!=nullptr || !s.empty()){
         if(!chacki.empty() && root == NULL && chacki.top() == false){
             if(!s.empty())
             root = s.top()->right;
             chacki.pop();
             chacki.push(true) ;
         }
         else if(!chacki.empty() && root == nullptr && chacki.top()== true){
            chacki.pop();
              if(!s.empty()){
             ans.push_back(s.top()->data);
             s.pop();
            }
             if(!s.empty() && !chacki.empty() && chacki.top()== false){
             root = s.top()->right;
             
               if(!chacki.empty()){
                   chacki.pop();
               chacki.push(true) ;
               }
            }
            //  else if(!s.empty() && !chacki.empty() && chacki.top()== true){
            //      ans.push_back(root->data);
            //      s.pop();
            //      chacki.pop();
            //      if(!s.empty())
            //  }
           
         }
        else{
            s.push(root);
            chacki.push(false);
            root= root->left;
        }
    }
    return ans;
     
 }

beginners

tutorial

datastructures

algorithms

+1 more
47 views
0 replies
1 upvote

Interview problems

Postorder Traversal easy c++ solution using recursion

void postorder(TreeNode* temp, vector<int>&v)
{
  if(temp == NULL) return ;
    postorder(temp->left,v);
    
    postorder(temp->right, v);
    v.push_back(temp->data);
}
vector<int> postorderTraversal(TreeNode *root)
{
    vector<int>v;
   postorder(root,v);
   return v;
}

Day 6: Recursion

Day 13: Recursion

Day 12: Recursion

Postorder Binary Tree

+1 more
50 views
0 replies
1 upvote
profile

Interview problems

Java Easy Iterative Post Order Traversal Using Single Stack

 public static List<Integer> postorderTraversal(TreeNode<Integer> root) {

        // Write your code here

        Stack<TreeNode<Integer>> stack1 = new Stack<>();

        Set<TreeNode<Integer>> visited = new HashSet<>();

        List<Integer> traversals = new ArrayList<>();

 

        stack1.push(root);

 

        while(!stack1.isEmpty()){

            TreeNode<Integer> topTreeNode = stack1.peek();

            if(!visited.contains(topTreeNode)){

                visited.add(topTreeNode);

                if(null != topTreeNode.right){

                    stack1.push(topTreeNode.right);

                }

 

                if(null != topTreeNode.left){

                    stack1.push(topTreeNode.left);

                }

            }else{

                TreeNode<Integer> poppedNode = stack1.pop();

                traversals.add(poppedNode.data);

            }

        }

        return traversals;

    }

java

123 views
0 replies
1 upvote

Interview problems

Java Solution Using Two Stacks

import java.util.*;

 

public class Solution {

    public static List<Integer> postorderTraversal(TreeNode<Integer> root) {

        // Write your code here

        Stack<TreeNode<Integer>> st1=new Stack<>();

        Stack<TreeNode<Integer>> st2=new Stack<>();

        st1.push(root);

        while(!st1.isEmpty())

        {

            TreeNode<Integer> ele=st1.pop();

            st2.push(ele);

            if(ele.left!=null)

            {

                st1.push(ele.left);

            }

            if(ele.right!=null)

            {

                st1.push(ele.right);

            }

        }

 

        List<Integer> ans=new ArrayList<Integer>();

 

        while(!st2.isEmpty())

        {

            ans.add(st2.pop().data);

        }

 

        return ans;

    }

}

 

java

61 views
0 replies
0 upvotes

Interview problems

Java Solution Using Iterative Approach

import java.util.*;
import java.util.List;
public class Solution {
    public static List<Integer> postorderTraversal(TreeNode<Integer> root) {
        // Write your code here
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode<Integer>> st = new Stack<>();
        if(root != null)st.push(root);
        while(st.size() > 0){
            TreeNode <Integer> temp = st.peek();
            if(temp.left != null){
                st.push(temp.left);
                temp.left= null;
            }else if(temp.right != null){
                st.push(temp.right);
                temp.right = null;
            }else{
                list.add(temp.data);
                st.pop();
            }
        }
        return list;
    }
}
91 views
0 replies
0 upvotes

Interview problems

C++

void f(TreeNode *root, vector<int> &ans) {
    if(!root) return;
    f(root->left, ans);
    f(root->right, ans);
    ans.push_back(root->data);
}
vector<int> postorderTraversal(TreeNode *root) {
    vector<int> ans;
    f(root, ans);
    return ans;
}
149 views
0 replies
0 upvotes

Interview problems

c++ recursion

vector<int> v;

void postorder(TreeNode *root){

     if(root==nullptr){

        return ;

    }

    postorder(root->left);

    postorder(root->right);

    v.push_back(root->data);

}

vector<int> postorderTraversal(TreeNode *root)

{

    // Write your code here.

    v.clear();

    postorder(root);

    return v;

}

169 views
0 replies
1 upvote
Full screen
Console