#include<iostream> using namespace std; #define TREELEN 6 //數據結構定義 struct NODE { NODE* pLeft; //左子樹 NODE* pRight; //右子樹 char chValue; //該節點的值 }; void ReBuild(char* pPreOrder,char* pInOrder,int nTreeLen,NODE** pRoot) { //檢查邊界條件 if(pPreOrder==NULL || pInOrder==NULL) { return; } //獲得前序遍歷的第一個節點 NODE* pTemp = new NODE; pTemp->chValue = *pPreOrder; pTemp->pLeft = NULL; pTemp->pRight = NULL; //如果節點為空,把當前節點復制到根節點 if(*pRoot == NULL) { *pRoot = pTemp; } //如果當前樹長度為1,那麼已經是最後一個節點 if(nTreeLen == 1) { return; } //尋找子樹長度 char* pOrgInOrder = pInOrder; char* pLeftEnd = pInOrder; int nTempLen = 0; //找到左子樹的結尾 while(*pPreOrder != *pLeftEnd) { if(pPreOrder==NULL || pLeftEnd==NULL) { return; } nTempLen++; //記錄臨時長度,以免溢出 if(nTempLen > nTreeLen) { break; } pLeftEnd++; } //尋找左子樹長度 int nLeftLen = 0; nLeftLen = (int)(pLeftEnd-pOrgInOrder); //尋找右子樹長度 int nRightLen = 0; nRightLen = nTreeLen - nLeftLen - 1; //重建左子樹 if(nLeftLen > 0) { ReBuild(pPreOrder+1,pInOrder,nLeftLen,&((*pRoot)->pLeft)); } //重建右子樹 if(nRightLen > 0) { ReBuild(pPreOrder+nLeftLen+1,pInOrder+nLeftLen+1,nRightLen,&((*pRoot)->pRight)); } } //前序遍歷結果 void PrePrint(NODE* pRoot) { if(pRoot == NULL) { return; } cout<<pRoot->chValue<<" "; PrePrint(pRoot->pLeft); PrePrint(pRoot->pRight); } //中序遍歷結果 void InPrint(NODE* pRoot) { if(pRoot == NULL) { return; } InPrint(pRoot->pLeft); cout<<pRoot->chValue<<" "; InPrint(pRoot->pRight); } void main() { char szPreOrder[TREELEN] = {'a','b','d','c','e','f'}; char szInOrder[TREELEN] = {'d','b','a','e','c','f'}; NODE* pRoot = NULL; ReBuild(szPreOrder,szInOrder,TREELEN,&pRoot); PrePrint(pRoot); cout<<endl<<endl;; InPrint(pRoot); cout<<endl; } /* a b d c e f d b a e c f */