http://ac.jobdu.com/problem.php?cid=1040&pid=31
- 题目描述:
-
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
- 输入:
-
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
- 输出:
-
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
- 样例输入:
-
ABC BAC FDXEAG XDEFAG
- 样例输出:
-
BCA XEDGAF
// 题目32:二叉树遍历.cpp: 主项目文件。 #include "stdafx.h" #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std;; const int N=31; typedef struct BitNode { char value; BitNode *lchild,*rchild; }BitNode,*BiTree; void CreatTree(BitNode *&root,char *pre,int l1,int r1,char *in,int l2,int r2) { if(l1<=r1&&l2<=r2) { int key=pre[l1]; int midIndex=-1; for(int i=l2;i<=r2;i++) { if(in[i]==key) { midIndex=i; break; } } root=(BitNode *)malloc(sizeof(BitNode)); root->value=key; root->lchild=NULL; root->rchild=NULL; int llen=midIndex-l2; CreatTree(root->lchild, pre, l1+1, l1+llen, in, l2, midIndex-1); CreatTree(root->rchild, pre, l1+llen+1, r1, in, midIndex+1, r2); } } void postOrderTraverse(BitNode *&root) { if(root->lchild) postOrderTraverse(root->lchild); if(root->rchild) postOrderTraverse(root->rchild); printf("%c",root->value); } int main() { char pre[N],in[N]; while(scanf("%s",pre)!=EOF) { scanf("%s",in); int len1=strlen(pre); int len2=strlen(in); BitNode *root=NULL; CreatTree(root,pre,0,len1-1,in,0,len2-1); postOrderTraverse(root); printf("\n"); } return 0; }