题意:
给出一棵二叉树的中序和后序遍历,求它的前序遍历。
代码如下:
#include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <iostream> #include <cstdlib> using namespace std; struct TNode { char cInfo; TNode * pLeft; TNode * pRight; }; #define NULL 0 #define LEN sizeof(TNode) typedef TNode * pBTNode; void vCreatTree(string sMidOrd,string sPostOrd,pBTNode pRoot) { int nLen,nPos; char cData; string sMidOrd1,sMidOrd2,sPostOrd1,sPostOrd2; pBTNode pLSon,pRSon; nLen=sPostOrd.size(); cData=sPostOrd[nLen-1]; pRoot->cInfo=cData; pRoot->pLeft=NULL; pRoot->pRight=NULL; nPos=sMidOrd.find(cData); if(nLen>1) { if(nPos>0) { sMidOrd1=sMidOrd.substr(0,nPos); sPostOrd1=sPostOrd.substr(0,nPos); pLSon=(struct TNode *)malloc(LEN); pRoot->pLeft=pLSon; vCreatTree(sMidOrd1,sPostOrd1,pLSon); } if(nLen-1>nPos) { sMidOrd2=sMidOrd.substr(nPos+1,nLen-nPos-1); sPostOrd2=sPostOrd.substr(nPos,nLen-nPos-1); pRSon=(struct TNode *)malloc(LEN); pRoot->pRight=pRSon; vCreatTree(sMidOrd2,sPostOrd2,pRSon); } } } //获得前序遍历 string sGetPreOrd(pBTNode pRoot) { string sRet; sRet=""; if(pRoot!=NULL) { sRet+=pRoot->cInfo; sRet+=sGetPreOrd(pRoot->pLeft); sRet+=sGetPreOrd(pRoot->pRight); } return sRet; } // 删除树 void vDeleteTree(pBTNode pRoot) { if(pRoot->pLeft!=NULL) { vDeleteTree(pRoot->pLeft); free(pRoot->pLeft); pRoot->pLeft=NULL; } if(pRoot->pRight!=NULL) { vDeleteTree(pRoot->pRight); free(pRoot->pRight); pRoot->pRight=NULL; } } //输出 void vOutput(string sOut) { cout << sOut << endl; } int main() { string sMidOrd,sPostOrd,sPreOrd; pBTNode pRoot; while(cin >> sMidOrd >> sPostOrd) { pRoot=(struct TNode *)malloc(LEN); vCreatTree(sMidOrd,sPostOrd,pRoot); sPreOrd=sGetPreOrd(pRoot); vOutput(sPreOrd); //vDeleteTree(pRoot); free(pRoot); } return 0; } /* DCFEAB DFECBA */
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-18 22:45:57