虽然结帖了,还是发一个吧
/*Function:
* rebirth the tree by it's preorder squence and inorder squence.
*Prototype:
* struct btnode * Create_Tree(int * PreorderSquen, int * InorderSquen, int SquenLength)
*Input parameter:
* PreorderSquen: an integer pointer, denote the start address of the preorder squence
* InorderSquen: an integer pointer, denote the start address of the inorder squence
* SquenceLength: an integer, denote the length of the squence, namely the number of the tree's node
*Output:
* a btnode pointer, point the root of the created tree
*Notice:
* the pointers, Preorder and Inorder, shouldn't be null
* also, the two squence should have the same set of nodes
* the value of SquenLength should be bigger than zero
*/
struct btnode * Create_Tree(int * PreorderSquen, int * InorderSquen, int SquenLength)
{
int position_inorder; //save where the head element of preorder squence is in the inoder squence
struct btnode * head; //point the root of the tree
if (SquenLength > 0)
{
//initialize the new node
head = (struct btnode *)malloc(sizeof(struct btnode));
head->value = *PreorderSquen;
head->LeftChild = NULL;
head->RightChild = NULL;
position_inorder = Find(*PreorderSquen, InorderSquen, SquenLength);
/*here ignore the condition that the function Find return -1*/
head->LeftChild = Create_Tree(PreorderSquen++, InorderSquen, position_inorder);
head->RightChild = Create_Tree((PreorderSquen + position_inorder), (InorderSquen + position_inorder), (SquenceLength - position_inorder));
return head;
}
else
return NULL;
}
//return the element x position in object_squence, from 1 to length
int Find(int x, int * object_squence, int length)
{
int i;
i = 0;
while ((i < length) && (*(object_squence + i) != x))
{
i++;
}
if (i < length)
{
return (i+1);
}
else
{
return -1;
}
}