題目描述:已知一棵樹的前序和中序周遊結果,求其後序結果。
分析:
對于一個二叉樹而言,若知道其前序和中序,那麼就能唯一确定其後序。方法就是通過每次判斷,遞歸的得到每棵子樹。
Node* Rebuild(int *pre, int *mid, int length)
{
if(pre == NULL || mid == NULL || length < )
return NULL;
return Rebuild(pre, pre + length - , mid, mid + length - );
}
Node *ReBuild(int *prestart, int *preend, int *midstart, int *midend)
{
int rootValue = prestart[];
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();
}
}
int *rootIndex = midstart;
while(rootIndex <= midend && *rootIndex != rootValue)
rootIndex++;
if(rootIndex > midend)
{
printf("Invaild input\n");
exit();
}
int leftlen = rootIndex - midstart;
int *preleftend = prestart + leftlen;
if(leftlen > )
{
root->left = Rebuild(prestart, preleftend, midstart, rootIndex - );
}
if(left < midend - midstart)
{
root->right = Rebuild(preleftend + , preend, rootIndex + , midend);
}
return root;
}