Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
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.
