题目描述:已知一棵树的前序和中序遍历结果,求其后序结果。
分析:
对于一个二叉树而言,若知道其前序和中序,那么就能唯一确定其后序。方法就是通过每次判断,递归的得到每棵子树。
Node* Rebuild(int *pre, int *mid, int length)
{
if(pre == NULL || mid == NULL || length < 1)
return NULL;
return Rebuild(pre, pre + length - 1, mid, mid + length - 1);
}
Node *ReBuild(int *prestart, int *preend, int *midstart, int *midend)
{
int rootValue = prestart[0];
Node *root = new Node;
root->left = NULL;
root->right = NULL;
root->data = rootValue;
if(prestart == preend)
{
if(minstart == midend && *prestart == *midstart)
return root;
else
{
printf("Invalid input!\n");
exit(1);
}
}
int *rootIndex = midstart;
while(rootIndex <= midend && *rootIndex != rootValue)
rootIndex++;
if(rootIndex > midend)
{
printf("Invaild input\n");
exit(1);
}
int leftlen = rootIndex - midstart;
int *preleftend = prestart + leftlen;
if(leftlen > 0)
{
root->left = Rebuild(prestart, preleftend, midstart, rootIndex - 1);
}
if(left < midend - midstart)
{
root->right = Rebuild(preleftend + 1, preend, rootIndex + 1, midend);
}
return root;
}