// C program to construct tree using
// inorder and postorder traversals
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left;
struct Node *right;
};
struct Node *createNode(int x);
// Function to find index of value in arr[start...end]
// The function assumes that value is present in in[]
int search(int arr[], int start, int end, int value) {
int i;
for (i = start; i <= end; i++) {
if (arr[i] == value)
break;
}
return i;
}
// Recursive function to construct binary tree of size n
// from Inorder traversal in[] and Postorder traversal
// post[].
struct Node *buildUtil(int inorder[], int postorder[],
int inStart, int inEnd, int *pIndex) {
if (inStart > inEnd)
return NULL;
// Pick current node from Postorder traversal using
// postIndex and decrement postIndex
struct Node *node = createNode(postorder[*pIndex]);
(*pIndex)--;
// If this node has no children then return
if (inStart == inEnd)
return node;
// Else find the index of this node in Inorder traversal
int inIndex = search(inorder, inStart, inEnd, node->data);
// Using index in Inorder traversal, construct left and
// right subtrees
node->right = buildUtil(inorder, postorder, inIndex + 1, inEnd, pIndex);
node->left = buildUtil(inorder, postorder, inStart, inIndex - 1, pIndex);
return node;
}
// This function mainly initializes index of root
// and calls buildUtil()
struct Node *buildTree(int inorder[], int postorder[], int n) {
int pIndex = n - 1;
return buildUtil(inorder, postorder, 0, n - 1, &pIndex);
}
// Print the preorder of a binary tree
void printPreorder(struct Node *node) {
if (node == NULL)
return;
printf("%d ", node->data);
printPreorder(node->left);
printPreorder(node->right);
}
struct Node *createNode(int x) {
struct Node *node =
(struct Node *)malloc(sizeof(struct Node));
node->data = x;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
int inorder[] = {4, 8, 2, 5, 1, 6, 3, 7};
int postorder[] = {8, 4, 5, 2, 6, 7, 3, 1};
int n = sizeof(inorder) / sizeof(inorder[0]);
struct Node *root = buildTree(inorder, postorder, n);
printPreorder(root);
return 0;
}