-
题目描述:
-
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
-
输入:
-
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
-
输出:
-
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
-
样例输入:
-
ABC BAC FDXEAG XDEFAG
-
样例输出:
-
BCA XEDGAF
-
答疑:
- 解题遇到问题?分享解题心得?讨论本题请访问: http://t.jobdu.com/thread-7801-1-1.html
-
-
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct node{ int data; struct node* lchild; struct node* rchild; }Node; Node *create(char *pre, char *in, int len) { if(len == 0) return NULL; Node *root; root =(Node *)malloc(sizeof(struct node)); int preindex=0; int inindex; root->data = *pre; //printf("pre=%c\n",*pre); for(inindex = 0; inindex < len; inindex++) { if(in[inindex] == *pre) break; } root->lchild = create(pre+1,in,inindex); root->rchild = create(pre+inindex+1,in+inindex+1,len-inindex-1); return root; } void postorder(Node *root) { if(root != NULL) { postorder(root->lchild); postorder(root->rchild); printf("%c",root->data); } } int main() { char preorder[27]; char inorder[27]; int len; while(scanf("%s",preorder)!= EOF) { len = strlen(preorder); scanf("%s",inorder); Node *root; root = create(preorder,inorder,len); postorder(root); printf("\n"); } }
其实不需要return node,只要在26行后面打印出root->data即按后序遍历输出。