Given the Infix and Postfix traversal, construct the tree

Given the Infix and Postfix traversal, construct the tree

Answer:
Possible only in cases where there are unique elements.


/**
* Program to construct a tree from a Infix and prefix traversals.
* */
#include
using namespace std;

struct TreeNode
{
char node;
TreeNode *left;
TreeNode *right;
TreeNode(char ch)
{
this->node = ch;
this->left = 0;
this->right = 0;
}
};
template
TreeNode* CtorTree(RandIter infix_begin, RandIter infix_end, RandIter postfix_begin, RandIter postfix_end)
{
/* Nothing to add */
if( (infix_begin == infix_end) || (postfix_begin == postfix_end) )
return NULL;
/* The current element in the postfix becomes the root */
TreeNode *tnode = new TreeNode(*postfix_begin);
/* Search for the root in infix representation from reverse */
RandIter j = infix_end;
while( j>= infix_begin )
{
--j;
if (*j == *postfix_begin)
break;
}
ptrdiff_t num_nodes = j - infix_begin;
++postfix_begin;

/* we have found the corresponding root at location j */
TreeNode *left_subtree = CtorTree(infix_begin, j, postfix_begin , postfix_begin + num_nodes);
TreeNode *right_subtree = CtorTree(j+1, infix_end, postfix_begin + num_nodes , postfix_end );
tnode->left = left_subtree;
tnode->right = right_subtree;
return tnode;
}

void Infix_traversal(TreeNode* n)
{
if (n)
{
Infix_traversal(n->left);
cout << n->node;
Infix_traversal(n->right);
}
}

int main(int argc, char ** argv)
{
if ( argc != 3 )
{
cerr << "Usage:" << argv[0] << " infix prefix " << endl;
}
else
{
char *infix = strdup(argv[1]);
char *prefix = strdup(argv[2]);
TreeNode *tree = CtorTree(infix, infix+strlen(infix), prefix, prefix + strlen(prefix));
cout << endl << "The Infix traversal of the constructed tree : " << endl;
Infix_traversal (tree);
free (infix);
free (prefix);
}
return 0;
}

2 comments:

pavan said...

I wnated to know that in the while look the *j should be compared with the *postfix_end

pavan said...

RandIter j = infix_end;
while( j>= infix_begin )
{
--j;
if (*j == *postfix_end)
break;
}
ptrdiff_t num_nodes = j - infix_begin;
--postfix_end;

Can also be written. Right?