Pseudocode for Constructing a binary tree from its preorder and inorder traversal.
Lets say there is a tree as follows.
1
/ \
2 3
/ \ / \
4 5 6 7
Inorder Traversal : 4 2 5 1 6 3 7
Preorder Traversal : 1 2 4 5 3 6 7.
We will built a binary from the inorder and preorder traversal .
Lets call the function with the following parameters with the root containing the pointer to the newly created tree.
root = builtTree(inorderArray,0,inorderArray.size-1,0)
Struct node
{
int data;
node * left;
node* right;
}
node buildTree( int[] inorderArray, int start , int end, int pos)
{
if (inorderArray==null)
return null;
node elem = new mode();
if(start==end)
{
elem->data = inorderArray[pos];
return node;
}
else
{
pos = findElementInPreoder(inorderArray,start,end,pos);
node->left = buildTree( inorderArray, 0, pos-1, pos++);
node->right = buildTree( inorderArray, pos+1, end, pos++);
}
}
}
int findElementInPreoder(int[] inorderArray, start,end,int pos)
{
for (int i = start;i<=end;i++)
{
if(inorderArray[i]==preorderArray[pos])
{
return i;
}
}
}