当我在整数数组中有前序遍历和中序遍历时,给出输出树的后序遍历的代码。我如何用给定的 inorder 和 postorder 数组同样获得预购?
void postorder( int preorder[], int prestart, int inorder[], int inostart, int length)
{
if(length==0) return; //terminating condition
int i;
for(i=inostart; i<inostart+length; i++)
if(preorder[prestart]==inorder[i])//break when found root in inorder array
break;
postorder(preorder, prestart+1, inorder, inostart, i-inostart);
postorder(preorder, prestart+i-inostart+1, inorder, i+1, length-i+inostart-1);
cout<<preorder[prestart]<<" ";
}
这是 preorder() 的原型
void preorder(int inorderorder[], int inostart, int postorder[], int poststart, int length)
使用 postorder() 它将是
int preorder[6]={6,4,1,5,8,9};
int inorder[6]={1,4,5,6,8,9};
postorder( preorder,0,inorder,0,6);
输出将是
1 5 4 9 8 6
下面是 print_preorder() 的错误代码,下面仍然无法正常工作
void print_preorder( int inorder[], int inostart, int postorder[], int poststart, int length)
{
if(length==0) return; //terminating condition
int i;
for(i=inostart; i<inostart+length; i++)
if(postorder[poststart+length-1]==inorder[i])
break;
cout<<postorder[poststart+length-1]<<" ";
print_preorder(inorder, inostart , postorder, poststart, i-inostart);
print_preorder(inorder, inostart+i-poststart+1, postorder, i+1, length-i+inostart-1);
}