/*根据先序遍历和中序遍历的字符串,构造出树*/ /*先序遍历树,使用递归和非递归两种方法*/ #include <iostream> using namespace std; struct NODE { NODE* pLeft; NODE* pRight; char chValue; }; #define STACKSIZE 10 typedef NODE *datatype; typedef struct _stack_ { datatype data[STACKSIZE]; int top; }stack; void CreateStack(stack* s) { memset(s->data, 0, STACKSIZE); s->top = -1; return; } int Push(stack* s, datatype value) { s->top++; if (s->top < STACKSIZE) { s->data[s->top] = value; return 0; } else return -1; } int Pop(stack* s, datatype* p) { if (s->top < 0) return -1; else { *p = s->data[s->top]; s->top--; return 0; } } int DeleteStack(stack s) { return 0; } //非递归先序遍历 void preorder(NODE* root) { stack theStack; NODE* curNode; CreateStack(&theStack); Push(&theStack, root); while(Pop(&theStack, &curNode) != -1) { if (curNode) { printf("%c", curNode->chValue); Push(&theStack, curNode->pRight); Push(&theStack, curNode->pLeft); } } DeleteStack(theStack); } //递归先序遍历 void recurPreOrder(NODE* root) { if (root != NULL) { printf("%c", root->chValue); if (root->pLeft != NULL) recurPreOrder(root->pLeft); if (root->pRight != NULL) recurPreOrder(root->pRight); } } void Rebuild(char* pPreOrder, char* pInOrder, int nTreeLen, NODE** pRoot) { if (pPreOrder==NULL && pInOrder==NULL) return; NODE* t = new NODE; t->chValue = *pPreOrder; t->pLeft = NULL; t->pRight = NULL; if (*pRoot == NULL) *pRoot = t; if (nTreeLen == 1) return; char* p = pInOrder; int nLeftLen = 0; while(*p != *pPreOrder) { if (p == NULL) return; nLeftLen++; if (nLeftLen >= nTreeLen) break; p++; } int nRightLen = nTreeLen - nLeftLen - 1; char* pLeftPreOrder = pPreOrder + 1; char* pRightPreOrder = pPreOrder + 1 + nLeftLen; char* pLeftInOrder = pInOrder; char* pRightInOrder = p + 1; if (nLeftLen >= 1) Rebuild(pLeftPreOrder, pLeftInOrder, nLeftLen, &((*pRoot)->pLeft)); if (nRightLen >= 1) Rebuild(pRightPreOrder, pRightInOrder, nRightLen, &((*pRoot)->pRight)); return; } int main() { char* pPreOrder = "abdcef"; char* pInOrder = "dbaecf"; int nTreeLen = strlen(pPreOrder); NODE* pRoot = NULL; Rebuild(pPreOrder, pInOrder, nTreeLen, &pRoot); preorder(pRoot); //recurPreOrder(pRoot); return 0; }