根据前序遍历和中序遍历求出二叉树并打印

#define MAX 100
typedef struct node {
   char info;
   struct node *llink,*rlink;
}TNODE;

char pred[MAX],inod[MAX];
TNODE *restore(char *,char *,int);
int main(int argc,char **argv)
{
   TNODE *root;
   if (argc<3) exit(0);
   strcpy(pred,argv[1]);
   strcpy(inod,argv[2]);
   root=restore(pred,inod,strlen(pred));
   postorder(root);
   printf("\n\n");
   return 1;
}

TNODE *restore(char *ppos,char *ipos,int n)
{
   TNODE *ptr;
   char *rpos;
   int k;
   if (n<=0) return NULL;
   ptr=(TNODE *)malloc(sizeof(TNODE));
   ptr->info=*ppos;
   for (rpos=ipos;ipos<ipos;rpos++)
   if (*rpos==*ppos) break;
   k=rpos-ipos;
   ptr->llink=restore(ppos+1,ipos,k);
   ptr->rlink=restore(ppos+1+k,ipos+k+1,n-1-k);
   return ptr;
}

postorder(TNODE *ptr)
{
   if (ptr==NULL) return;
   postorder(ptr->llink);
   postorder(ptr->rlink);
   printf("%c",ptr->info);
}
上一篇:二叉树的三种遍历方式,含demo(递归与非递归)


下一篇:【小Y学算法】⚡️每日LeetCode打卡⚡️——40.二叉树的后序遍历