/* 根据二叉树的后序和中序确定前序序列 输入: ACBFGED ABCDEFG CDAB CBAD 输出: DBACEGF BCAD 采用简便方法:将根节点放在最后 */ /* 关键: 1 循环中一找到自己想要的,要立即跳出 if(strMid[i] == strPost[e1]) { iRootIdx = i; break; } 2 循环的界限处一定多加留意,for(int i = s2; i <= e2;i++) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXSIZE 1024 /* void build(char* strFront,char* strMid,char* strPost,int iLen) { if(iLen <= 0) { return; } int iSize = strchr(strMid,strFront[0]) - strMid;//求得是左子树长度 build(strFront+1,strMid,strPost,iSize); build(strFront+iSize+1,strMid+iSize+1,strPost,iLen-iSize-1); strPost[iLen-1] = strFront[0]; } */ typedef struct TNode { char ch; struct TNode* left,*right; }Node; int loc; Node node[50]; Node* createNode() { node[loc].left = node[loc].right = NULL; return &node[loc++]; } void frontOrder(Node* headNode) { if(headNode) { printf("%c",headNode->ch); frontOrder(headNode->left); frontOrder(headNode->right); } } char strMid[MAXSIZE],strPost[MAXSIZE]; Node* build(int s1,int e1,int s2,int e2) { Node* retNode = createNode(); retNode->ch = strPost[e1]; int iRootIdx; for(int i = s2; i <= e2;i++) { if(strMid[i] == strPost[e1]) { iRootIdx = i; break; } } if(iRootIdx != s2)//若头结点在中序的初始位置,表明左子树为空 { retNode->left = build(s1,s1+(iRootIdx-s2)-1,s2,iRootIdx-1);//选取后序队列,中序提供的位置是不变的 } if(iRootIdx != e2)//若头结点在中序结束位置,表明右子树为空 { retNode->right = build(s1+(iRootIdx-s2),e1-1,iRootIdx+1,e2); } return retNode; } int main(int argc,char* argv[]) { while(EOF != scanf("%s %s",strPost,strMid)) { loc = 0; int iPostLen = strlen(strPost); int iMidLen = strlen(strMid); Node* headNode = build(0,iPostLen-1,0,iMidLen-1); frontOrder(headNode); } system("pause"); return 0; }