The Wayback Machine - https://web.archive.org/web/20240828080651/https://www.geeksforgeeks.org/postorder-traversal-of-binary-tree/
Open In App

Postorder Traversal of Binary Tree

Last Updated : 17 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
74.96%
1.2L

Postorder traversal is defined as a type of tree traversal which follows the Left-Right-Root policy such that for each node:

  • The left subtree is traversed first
  • Then the right subtree is traversed
  • Finally, the root node of the subtree is traversed
Postorder traversal

Postorder traversal

Algorithm for Postorder Traversal of Binary Tree:

The algorithm for postorder traversal is shown as follows:

Postorder(root):

  1. If root is NULL then return
  2. Postorder (root -> left)
  3. Postorder (root -> right)
  4. Process root (For example, print(root->data))

How does Postorder Traversal of Binary Tree Work?

Consider the following tree:

Example of Binary Tree

Example of Binary Tree

If we perform a postorder traversal in this binary tree, then the traversal will be as follows:

Step 1: The traversal will go from 1 to its left subtree i.e., 2, then from 2 to its left subtree root, i.e., 4. Now 4 has no subtree, so it will be visited.

Node 4 is visited

Node 4 is visited

Step 2: As the left subtree of 2 is visited completely, now it will traverse the right subtree of 2 i.e., it will move to 5. As there is no subtree of 5, it will be visited.

Node 5 is visited

Node 5 is visited

Step 3: Now both the left and right subtrees of node 2 are visited. So now visit node 2 itself.

Node 2 is visited

Node 2 is visited

Step 4: As the left subtree of node 1 is traversed, it will now move to the right subtree root, i.e., 3. Node 3 does not have any left subtree, so it will traverse the right subtree i.e., 6. Node 6 has no subtree and so it is visited.

Node 6 is visited

Node 6 is visited

Step 5: All the subtrees of node 3 are traversed. So now node 3 is visited.

Node 3 is visited

Node 3 is visited

Step 6: As all the subtrees of node 1 are traversed, now it is time for node 1 to be visited and the traversal ends after that as the whole tree is traversed.

The complete tree is visited

The complete tree is visited

So the order of traversal of nodes is 4 -> 5 -> 2 -> 6 -> 3 -> 1.

Program to implement Postorder Traversal of Binary Tree

Below is the code implementation of the postorder traversal:

C++
// C++ program for postorder traversals

#include <bits/stdc++.h>
using namespace std;

// Structure of a Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
    Node(int v)
    {
        data = v;
        left = right = NULL;
    }
};

// Function to print postorder traversal
void printPostorder(struct Node* node)
{
    if (node == NULL)
        return;

    // First recur on left subtree
    printPostorder(node->left);

    // Then recur on right subtree
    printPostorder(node->right);

    // Now deal with the node
    cout << node->data << " ";
}

// Driver code
int main()
{
    struct Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->right = new Node(6);

    // Function call
    cout << "Postorder traversal of binary tree is: \n";
    printPostorder(root);

    return 0;
}
Java
// Java program for postorder traversals
import java.util.*;

// Structure of a Binary Tree Node
class Node {
    int data;
    Node left, right;
    Node(int v)
    {
        data = v;
        left = right = null;
    }
}

class GFG {
    
    // Function to print postorder traversal
    static void printPostorder(Node node)
    {
        if (node == null)
            return;

        // First recur on left subtree
        printPostorder(node.left);

        // Then recur on right subtree
        printPostorder(node.right);

        // Now deal with the node
        System.out.print(node.data + " ");
    }

    // Driver code
    public static void main(String[] args)
    {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(6);

        // Function call
        System.out.println("Postorder traversal of binary tree is: ");
        printPostorder(root);
    }
}
// This code is contributed by prasad264
Python
# Python program for postorder traversals

# Structure of a Binary Tree Node


class Node:
    def __init__(self, v):
        self.data = v
        self.left = None
        self.right = None

# Function to print postorder traversal


def printPostorder(node):
    if node == None:
        return

    # First recur on left subtree
    printPostorder(node.left)

    # Then recur on right subtree
    printPostorder(node.right)

    # Now deal with the node
    print(node.data, end=' ')


# Driver code
if __name__ == '__main__':
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(6)

    # Function call
    print("Postorder traversal of binary tree is:")
    printPostorder(root)
C#
// C# program for postorder traversals

using System;

// Structure of a Binary Tree Node
public class Node {
    public int data;
    public Node left, right;
    public Node(int v)
    {
        data = v;
        left = right = null;
    }
}

public class GFG {

    // Function to print postorder traversal
    static void printPostorder(Node node)
    {
        if (node == null)
            return;

        // First recur on left subtree
        printPostorder(node.left);

        // Then recur on right subtree
        printPostorder(node.right);

        // Now deal with the node
        Console.Write(node.data + " ");
    }

    static public void Main()
    {

        // Code
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(6);

        // Function call
        Console.WriteLine(
            "Postorder traversal of binary tree is: ");
        printPostorder(root);
    }
}

// This code is contributed by karthik.
JavaScript
// Structure of a Binary Tree Node
class Node {
  constructor(v) {
    this.data = v;
    this.left = null;
    this.right = null;
  }
}

// Function to print postorder traversal
function printPostorder(node) {
  if (node == null) {
    return;
  }

  // First recur on left subtree
  printPostorder(node.left);

  // Then recur on right subtree
  printPostorder(node.right);

  // Now deal with the node
  console.log(node.data + " ");
}

// Driver code
function main() {
  let root = new Node(1);
  root.left = new Node(2);
  root.right = new Node(3);
  root.left.left = new Node(4);
  root.left.right = new Node(5);
  root.right.right = new Node(6);

  // Function call
  console.log("Postorder traversal of binary tree is: \n");
  printPostorder(root);
}

main();

Output
Postorder traversal of binary tree is: 
4 5 2 6 3 1 

Explanation:

How postorder traversal works

How postorder traversal works

Complexity Analysis:

Time Complexity: O(N) where N is the total number of nodes. Because it traverses all the nodes at least once.
Auxiliary Space: O(1) if no recursion stack space is considered. Otherwise, O(h) where h is the height of the tree

  • In the worst case, h can be the same as N (when the tree is a skewed tree)
  • In the best case, h can be the same as logN (when the tree is a complete tree)

Use cases of Postorder Traversal:

Some use cases of postorder traversal are:

  • This is used for tree deletion.
  • It is also useful to get the postfix expression from an expression tree.

Related articles:



Similar Reads

Find postorder traversal of BST from preorder traversal
Given an array representing preorder traversal of BST, print its postorder traversal. Examples: Input : 40 30 35 80 100 Output : 35 30 100 80 40 Input : 40 30 32 35 80 90 100 120 Output : 35 32 30 120 100 90 80 40 Prerequisite: Construct BST from given preorder traversal Simple Approach: A simple solution is to first construct BST from a given preo
9 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Find n-th node in Postorder traversal of a Binary Tree
Given a Binary tree and a number N, write a program to find the N-th node in the Postorder traversal of the given Binary tree. Prerequisite: Tree Traversal Examples: Input : N = 4 11 / \ 21 31 / \ 41 51 Output : 31 Explanation: Postorder Traversal of given Binary Tree is 41 51 21 31 11, so 4th node will be 31. Input : N = 5 25 / \ 20 30 / \ / \ 18
13 min read
Find parent of given node in a Binary Tree with given postorder traversal
Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first [Tex]2^{N}-1 [/Tex] natural numbers [Tex](1, 2, ... 2^{N}-1) [/Tex] For N = 3, the Tree will be - 7 / \ 3 6 / \ / \ 1 2 4 5 Examples: Input: N = 4, K = 5 Output: 6 Explan
9 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Construct a Complete N-ary Tree from given Postorder Traversal
Given an array arr[] of size M that contains the post-order traversal of a complete N-ary tree, the task is to generate the N-ary tree and print its preorder traversal. A complete tree is a tree where all the levels of the tree are completely filled, except may be for the last level but the nodes in the last level are as left as possible. Examples:
13 min read
Level order traversal of Binary Tree using Morris Traversal
Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two observations for the traversal of the tree using Mor
11 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11 Post Order: 12 8 4 9 5 2 6 10 11 7 3 1 In Order: 8 12 4 2 9 5 1 6
9 min read
Construct a BST from given postorder traversal using Stack
Given postorder traversal of a binary search tree, construct the BST.For example, If the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. 10 / \ 5 40 / \ \ 1 7 50 Input : 1 7 5 50 40 10 Output : Inorder traversal of the constructed tree: 1 5 7 10 40 50 If the given traversa
9 min read
Iterative Postorder traversal | Set 3
We have seen different ways of performing postorder traversal on Binary Trees. Post Order Traversal.Iterative Postorder Traversal using Two Stacks.Iterative Postorder Traversal using One Stack. Here is another way of performing the postorder traversal on a Binary Tree iteratively using a single stack.Consider the Below Terminologies: 0 - Left eleme
7 min read
Print Postorder traversal from given Inorder and Preorder traversals
AuxiliaryGiven Inorder and Preorder traversals of a binary tree, print Postorder traversal. Example: Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal is {4, 5, 2, 6, 3, 1} Traversals in the above example represents following tree 1 / \ 2 3 / \ \ 4 5 6Recommended PracticePos
15+ min read
Iterative Postorder Traversal | Set 1 (Using Two Stacks)
We have discussed iterative inorder and iterative preorder traversals. In this post, iterative postorder traversal is discussed, which is more complex than the other two traversals (due to its nature of non-tail recursion, there is an extra statement after the final recursive call to itself). Postorder traversal can easily be done using two stacks,
10 min read
Iterative Postorder Traversal | Set 2 (Using One Stack)
We have discussed a simple iterative postorder traversal using two stacks in the previous post. In this post, an approach with only one stack is discussed. The idea is to move down to leftmost node using left pointer. While moving down, push root and root's right child to stack. Once we reach leftmost node, print it if it doesn't have a right child
15+ min read
Morris traversal for Postorder
Perform Postorder Tree traversal using Morris Traversal. Examples: Input: 1 / \ 2 3 / \ / \ 6 7 8 9 Output: 6 7 2 8 9 3 1 Input: 5 / \ 2 3 / \ / \ 4 N 8 9 Output: 4 2 8 9 3 5 Approach: The approach to performing Morris Traversal for Postorder is similar to Morris traversal for Preorder except swapping between left and right node links. Create a vec
8 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Construct Full Binary Tree from given preorder and postorder traversals
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children. Illustration: Following are examples of Full Trees. 1 / \ 2 3 / \ / \ 4 5 6 7 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 It is not possibl
14 min read
Postorder successor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find Postorder successor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : Complexity Analysis:24 Output : 27 Input : 4 Output : 13 A simple solu
8 min read
Postorder predecessor of a Node in Binary Search Tree
Given a binary tree and a node in the binary tree, find the Postorder predecessor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 10 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : 24 Output : 10 A simple solution is to fir
8 min read
Construct a Binary Search Tree from given postorder
Given postorder traversal of a binary search tree, construct the BST. For example, if the given traversal is {1, 7, 5, 50, 40, 10}, then following tree should be constructed and root of the tree should be returned. 10 / \ 5 40 / \ \ 1 7 50Recommended PracticeConstruct BST from PostorderTry It! Method 1 ( O(n^2) time complexity ): The last element o
13 min read
Construct a Binary Tree from Postorder and Inorder
Given Postorder and Inorder traversals, construct the tree. Examples: Input: in[] = {2, 1, 3}post[] = {2, 3, 1} Output: Root of below tree 1 / \ 2 3 Input: in[] = {4, 8, 2, 5, 1, 6, 3, 7}post[] = {8, 4, 5, 2, 6, 7, 3, 1} Output: Root of below tree 1 / \ 2 3 / \ / \4 5 6 7 \ 8 Recommended PracticeTree from Postorder and InorderTry It! Approach: To s
15+ min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read
Check if given Preorder, Inorder and Postorder traversals are of same tree
Given Preorder, Inorder, and Postorder traversals of some tree. Write a program to check if they all are of the same tree. Examples: Input: Inorder -&gt; 4 2 5 1 3 Preorder -&gt; 1 2 4 5 3 Postorder -&gt; 4 5 2 3 1Output: YesExplanation: All of the above three traversals are of the same tree 1 / \ 2 3 / \ 4 5Input: Inorder -&gt; 4 2 5 1 3 Preorder
15+ min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 min read
If you are given two traversal sequences, can you construct the binary tree?
It depends on what traversals are given. If one of the traversal methods is Inorder then the tree can be constructed, otherwise not. Therefore, following combination can uniquely identify a tree. Inorder and Preorder. Inorder and Postorder. Inorder and Level-order. And following do not. Postorder and Preorder. Preorder and Level-order. Postorder an
1 min read
Construct Special Binary Tree from given Inorder traversal
Given Inorder Traversal of a Special Binary Tree in which the key of every node is greater than keys in left and right children, construct the Binary Tree and return root. Examples: Input: inorder[] = {5, 10, 40, 30, 28} Output: root of following tree 40 / \ 10 30 / \ 5 28 Input: inorder[] = {1, 5, 10, 40, 30, 15, 28, 20} Output: root of following
14 min read
Perfect Binary Tree Specific Level Order Traversal
Given a Perfect Binary Tree like below: Print the level order of nodes in following specific manner: 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels are trivial. While 3rd level: 4(left), 7(right), 5
15+ min read
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples: Input : 10 / \ 8 2 / \ 3 5 Output : 10 \ 8 \ 3 \ 5 \ 2 Explanation : The preorder traversal of given binary tree is 10 8 3 5 2. Method
15 min read
Build Binary Tree from BST such that it's level order traversal prints sorted data
Construct a Binary Tree from the given Binary Search Tree such that it's level order traversal outputs sorted data.Examples: Input: Output: 1 2 3 Input: Output: 1 2 3 4 5 Approach: Perform the inorder traversal of the given Binary Search Tree.Add each node in level order to the Binary Tree.Finally, print the level order traversal of the created Bin
12 min read
Article Tags :
Practice Tags :