
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Postorder traversal from given Inorder and Preorder traversals
Given with inorder and preorder of a tree program must find the postroder traversal and print the same
Input: Inorder traversal in[] = {4, 2, 5, 1, 3, 6} Preorder traversal pre[] = {1, 2, 4, 5, 3, 6} Output: Postorder traversal post[] = {4, 5, 2, 6, 3, 1}
Algorithm
START Step 1 -> declare function as find_value(int p, int in_order[], int n) Loop For i=0 and i<n and ++i IF in_order[i]==p Return i End IF End Step 2 -> declare function as postorder(int pre_order[], int in_order[], int n) Declare int variable as root = find_value(pre_order[0], in_order, n) IF root!=0 Call postorder(pre_order+1, in_order, root) End IF root !=n-1 Call postorder(pre_order+root+1, in_order+root+1,n-root-1) End Print pre_order[0] End Step 3 -> goto main() Declare int pre_order[] = {1, 2, 4, 5, 3, 6} Declare int in_order[] = {4, 2, 5, 1, 3, 6} Declare int size = sizeof(pre_order)/sizeof(pre_order[0]) Call postorder(pre_order, in_order, size) STOP
Example
#include <stdio.h> int find_value(int p, int in_order[], int n) { for (int i = 0; i < n; ++i) { if (in_order[i] == p) { return i; } } return -1; } int postorder(int pre_order[], int in_order[], int n) { int root = find_value(pre_order[0], in_order, n); if(root !=0 ) postorder(pre_order+1, in_order, root); if (root != n-1) postorder(pre_order+root+1, in_order+root+1, n-root-1); printf("%d ", pre_order[0]); } int main(int argc, char const *argv[]) { 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]); postorder(pre_order, in_order, size); return 0; }
Output
if we run the above program then it will generate the following output
4 5 2 6 3 1
Advertisements