#include <iostream>
#define TREELEN 6
using namespace std;

typedef struct Node
{
    char chValue;
    struct Node* pLeft;
    struct Node* pRight;
}*PNode;

void LastOrder(PNode root)
{
    if(root==0)return;
    LastOrder(root->pLeft);
    LastOrder(root->pRight);
    cout<<root->chValue<<" ";
}

PNode ReBuild(char* pPreOrder,char* pInOrder,int nTreeLen)
{

    if(nTreeLen==0)return 0;
    if(nTreeLen==1)
    {
        PNode pRoot = new Node();
        pRoot->chValue = pPreOrder[0];
        pRoot->pLeft = 0;
        pRoot->pRight = 0;
        return pRoot;
    }
    if(pPreOrder==0 || pInOrder==0)return 0;
    PNode pRoot = new Node();
    pRoot->chValue = pPreOrder[0];
    pRoot->pLeft = 0;
    pRoot->pRight = 0;
    char *pLeftEnd = pInOrder;
    int nLeftLen = 0;
    while(pLeftEnd!=0 && *pPreOrder != *pLeftEnd)
    {
        nLeftLen++;
        pLeftEnd++;
        if(nLeftLen>nTreeLen)return 0;
    }

    int nRightLen = nTreeLen - nLeftLen - 1;
    cout<<nLeftLen<<" "<<nRightLen<<endl;
    if(nLeftLen>0)
    {
        pRoot->pLeft = ReBuild(pPreOrder+1,pInOrder,nLeftLen);
    }
    if(nRightLen>0)
    {
        pRoot->pRight = ReBuild(pPreOrder+nLeftLen+1,pInOrder+nLeftLen+1,nRightLen);
    }
    return pRoot;
}

int main()
{
    char szPreOrder[TREELEN]={'a','b','d','c','e','f'};
    char szInOrder[TREELEN]={'d','b','a','e','c','f'};
    PNode root = ReBuild(szPreOrder,szInOrder,TREELEN);
    LastOrder(root);
    cout<<endl;
    return 0;
}

 

posted on 2012-11-24 16:40  吉大依恋  阅读(241)  评论(0编辑  收藏  举报