Print Postorder traversal from given Inorder and Preorder traversals

Given inorder and preorder traversals of a binary tree, we can construct the postorder traversal without actually building the tree. This approach uses the property that preorder gives us the root first, inorder helps us divide left and right subtrees, and postorder processes left subtree, then right subtree, and finally the root.

Syntax

void postorder(int pre_order[], int in_order[], int n);
int find_value(int element, int in_order[], int n);

Algorithm

1. Find the root element (first element of preorder) in inorder array
2. Recursively process left subtree (elements before root in inorder)
3. Recursively process right subtree (elements after root in inorder)
4. Print the root element

Example

Here's how to print postorder traversal from given inorder and preorder arrays −

#include <stdio.h>

int find_value(int element, int in_order[], int n) {
    for (int i = 0; i < n; ++i) {
        if (in_order[i] == element) {
            return i;
        }
    }
    return -1;
}

void postorder(int pre_order[], int in_order[], int n) {
    if (n <= 0) return;
    
    int root_index = find_value(pre_order[0], in_order, n);
    
    // Process left subtree
    if (root_index != 0) {
        postorder(pre_order + 1, in_order, root_index);
    }
    
    // Process right subtree
    if (root_index != n - 1) {
        postorder(pre_order + root_index + 1, in_order + root_index + 1, n - root_index - 1);
    }
    
    // Print root
    printf("%d ", pre_order[0]);
}

int main() {
    int pre_order[] = {1, 2, 4, 5, 3, 6};
    int in_order[] = {4, 2, 5, 1, 3, 6};
    int size = sizeof(pre_order) / sizeof(pre_order[0]);
    
    printf("Inorder: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", in_order[i]);
    }
    printf("<br>");
    
    printf("Preorder: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", pre_order[i]);
    }
    printf("<br>");
    
    printf("Postorder: ");
    postorder(pre_order, in_order, size);
    printf("<br>");
    
    return 0;
}
Inorder: 4 2 5 1 3 6 
Preorder: 1 2 4 5 3 6 
Postorder: 4 5 2 6 3 1 

How It Works

Tree Structure 1 2 3 4 5 6 Inorder: 4 2 5 1 3 6 Preorder: 1 2 4 5 3 6 Postorder: 4 5 2 6 3 1

The algorithm recursively divides the tree using the root position found in inorder traversal, processes left and right subtrees, then prints the root.

Conclusion

This method efficiently constructs postorder traversal from inorder and preorder arrays using recursion. The time complexity is O(n²) due to the linear search for root position in each recursive call.

Updated on: 2026-03-15T11:07:15+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements