Postorder traversal of Binary Tree without recursion and without stack

Prerequisite – Inorder/preorder/postorder traversal of tree
Given a binary tree, perform postorder traversal.

We have discussed below methods for postorder traversal.
1) Recursive Postorder Traversal.
2) Postorder traversal using Stack.
2) Postorder traversal using two Stacks.

In this method a DFS based solution is discussed. We keep track of visited nodes in a hash table.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program or postorder traversal
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
    int data;
    struct Node *left, *right;
};
  
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
void postorder(struct Node* head)
{
    struct Node* temp = head;
    unordered_set<Node*> visited;
    while (temp && visited.find(temp) == visited.end()) {
  
        // Visited left subtree
        if (temp->left && 
         visited.find(temp->left) == visited.end())
            temp = temp->left;
  
        // Visited right subtree
        else if (temp->right && 
        visited.find(temp->right) == visited.end())
            temp = temp->right;
  
        // Print node
        else {
            printf("%d ", temp->data);
            visited.insert(temp);
            temp = head;
        }
    }
}
  
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return (node);
}
  
/* Driver program to test above functions*/
int main()
{
    struct Node* root = newNode(8);
    root->left = newNode(3);
    root->right = newNode(10);
    root->left->left = newNode(1);
    root->left->right = newNode(6);
    root->left->right->left = newNode(4);
    root->left->right->right = newNode(7);
    root->right->right = newNode(14);
    root->right->right->left = newNode(13);
    postorder(root);
    return 0;
}

chevron_right


Output:

1 4 7 6 3 13 14 10 8 

Alternate Solution:
We can keep visited flag with every node instead of separate hash table.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program or postorder traversal
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
    int data;
    struct Node *left, *right;
    bool visited;
};
  
void postorder(struct Node* head)
{
    struct Node* temp = head;
    while (temp && temp->visited == false) {
  
        // Visited left subtree
        if (temp->left && temp->left->visited == false)
            temp = temp->left;
  
        // Visited right subtree
        else if (temp->right && temp->right->visited == false)
            temp = temp->right;
  
        // Print node
        else {
            printf("%d ", temp->data);
            temp->visited = true;
            temp = head;
        }
    }
}
  
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->visited = false;
    return (node);
}
  
/* Driver program to test above functions*/
int main()
{
    struct Node* root = newNode(8);
    root->left = newNode(3);
    root->right = newNode(10);
    root->left->left = newNode(1);
    root->left->right = newNode(6);
    root->left->right->left = newNode(4);
    root->left->right->right = newNode(7);
    root->right->right = newNode(14);
    root->right->right->left = newNode(13);
    postorder(root);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program or postorder traversal
class GFG
{
  
/* A binary tree node has data, 
    pointer to left child
    and a pointer to right child */
static class Node 
{
    int data;
    Node left, right;
    boolean visited;
}
  
static void postorder( Node head)
{
    Node temp = head;
    while (temp != null && 
            temp.visited == false)
    {
  
        // Visited left subtree
        if (temp.left != null && 
            temp.left.visited == false)
            temp = temp.left;
  
        // Visited right subtree
        else if (temp.right != null && 
                temp.right.visited == false)
            temp = temp.right;
  
        // Print node
        else 
        {
            System.out.printf("%d ", temp.data);
            temp.visited = true;
            temp = head;
        }
    }
}
  
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.visited = false;
    return (node);
}
  
/* Driver code*/
public static void main(String []args)
{
    Node root = newNode(8);
    root.left = newNode(3);
    root.right = newNode(10);
    root.left.left = newNode(1);
    root.left.right = newNode(6);
    root.left.right.left = newNode(4);
    root.left.right.right = newNode(7);
    root.right.right = newNode(14);
    root.right.right.left = newNode(13);
    postorder(root);
}
}
  
// This code is contributed by Arnab Kundu

chevron_right


Python3

“””Python3 program or postorder traversal “””

# A Binary Tree Node
# Utility function to create a
# new tree node
class newNode:

# Constructor to create a newNode
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.visited = False

def postorder(head) :

temp = head
while (temp and temp.visited == False):

# Visited left subtree
if (temp.left and
temp.left.visited == False):
temp = temp.left

# Visited right subtree
elif (temp.right and
temp.right.visited == False):
temp = temp.right

# Print node
else:
print(temp.data, end = ” “)
temp.visited = True
temp = head

# Driver Code
if __name__ == ‘__main__’:

root = newNode(8)
root.left = newNode(3)
root.right = newNode(10)
root.left.left = newNode(1)
root.left.right = newNode(6)
root.left.right.left = newNode(4)
root.left.right.right = newNode(7)
root.right.right = newNode(14)
root.right.right.left = newNode(13)
postorder(root)

# This code is contributed by
# SHUBHAMSINGH10

C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program or postorder traversal
using System;
  
class GFG
{
  
/* A binary tree node has data, 
    pointer to left child
    and a pointer to right child */
class Node 
{
    public int data;
    public Node left, right;
    public bool visited;
}
  
static void postorder( Node head)
{
    Node temp = head;
    while (temp != null && 
            temp.visited == false)
    {
  
        // Visited left subtree
        if (temp.left != null && 
            temp.left.visited == false)
            temp = temp.left;
  
        // Visited right subtree
        else if (temp.right != null && 
                temp.right.visited == false)
            temp = temp.right;
  
        // Print node
        else
        {
            Console.Write("{0} ", temp.data);
            temp.visited = true;
            temp = head;
        }
    }
}
  
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.visited = false;
    return (node);
}
  
/* Driver code*/
public static void Main(String []args)
{
    Node root = newNode(8);
    root.left = newNode(3);
    root.right = newNode(10);
    root.left.left = newNode(1);
    root.left.right = newNode(6);
    root.left.right.left = newNode(4);
    root.left.right.right = newNode(7);
    root.right.right = newNode(14);
    root.right.right.left = newNode(13);
    postorder(root);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right



Output:

1 4 7 6 3 13 14 10 8 

Time complexity of above solution is O(n2) in worst case we move pointer back to head after visiting every node.
Alternate solution using unordered_map in which we do not have to move pointer back to head, so time complexity is O(n).

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program or postorder traversal
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
    int data;
    struct Node *left, *right;
    bool visited;
};
  
void postorder(Node* root)
{
    Node* n = root;
    unordered_map<Node*, Node*> parentMap;
    parentMap.insert(pair<Node*, Node*>(root, nullptr));
  
    while (n) {
        if (n->left && parentMap.find(n->left) == parentMap.end()) {
            parentMap.insert(pair<Node*, Node*>(n->left, n));
            n = n->left;
        }
        else if (n->right && parentMap.find(n->right) == parentMap.end()) {
            parentMap.insert(pair<Node*, Node*>(n->right, n));
            n = n->right;
        }
        else {
            cout << n->data << " ";
            n = (parentMap.find(n))->second;
        }
    }
}
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->visited = false;
    return (node);
}
  
/* Driver program to test above functions*/
int main()
{
    struct Node* root = newNode(8);
    root->left = newNode(3);
    root->right = newNode(10);
    root->left->left = newNode(1);
    root->left->right = newNode(6);
    root->left->right->left = newNode(4);
    root->left->right->right = newNode(7);
    root->right->right = newNode(14);
    root->right->right->left = newNode(13);
    postorder(root);
    return 0;
}

chevron_right


Output:

1 4 7 6 3 13 14 10 8 


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.