Consider the following inorder and preorder traversal
inorder ={12, 25, 30, 37, 40, 50, 60, 62, 70, 75, 87}
preorder ={50, 25, 12, 37, 30, 40, 75, 62, 60, 70, 87}
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
2) Create a new tree node tNode with the data as picked element.
3) Find the picked element%u2019s index in Inorder. Let the index be inIndex.
4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.
6) return tNode.
#include<iostream>
#include<stdlib.h>
using namespace std;
class node
{ public:
int info;
node* left;
node* right;
};
int search(int arr[], int strt, int end, int value);
node* newNode(int info);
node* buildTree(int in[], int pre[], int inStrt, int inEnd)
{ static int preIndex = 0;
if (inStrt > inEnd)
return NULL;
node* tNode = newNode(pre[preIndex++]);
if (inStrt == inEnd)
return tNode;
int inIndex = search(in, inStrt, inEnd, tNode->info);
tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd);
return tNode;
}
int search(int arr[], int strt, int end, int value)
{ int i;
for (i = strt; i <= end; i++)
{
if (arr[i] == value)
return i;
}
}
node* newNode(int info)
{
node* Node = new node();
Node->info = info;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
void printInorder(node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout<<node->info<<" ";
printInorder(node->right);
}
int main()
{ int in[] = {12, 25, 30, 37, 40, 50, 60, 62, 70, 75, 87};
int pre[] = {50, 25, 12, 37, 30, 40, 75, 62, 60, 70, 87};
int len = sizeof(in) / sizeof(in[0]);
node* root = buildTree(in, pre, 0, len - 1);
cout << "Inorder traversal of the constructed tree is \n";
printInorder(root);
}
Inorder traversal of the constructed tree is
12 25 30 37 40 50 60 62 70 75 87
Process returned 0 (0x0) execution time : 0.174 s
Press any key to continue.
Comments