Traversal in Binary Trees II

Tuesday, 12 June 2012
,
Function to print the postorder given the preorder and inorder:

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);
  printf("%d ",preorder[prestart]);
}

Function to print the preorder given the postorder and inorder:

void preorder( int postorder[],int poststart,int inorder[],int inostart,int length)
{
  //printf("length=%d\n",length);
  if(length==0) return;//terminating condition
  int i;
  for(i=inostart;i<inostart+length;i++)
    if(postorder[poststart]==inorder[i])//break when found root in inorder array
        break;
  printf("%d ",postorder[poststart]);
  preorder(postorder,i-1,inorder,inostart,i-inostart);
  preorder(postorder,poststart-1,inorder,i+1,length-i+inostart-1);
}


Copyright @ 2013 code-craft. Designed by Templateism | MyBloggerLab