#include <stdio.h>
#include <stdlib.h>
#define TREELEN 6
struct Node
{
struct Node * pLeft;
struct Node * pRight;
char chValue;
};
void ReBuildTree(char * pPreOrder, char * pInOrder, int nTreeLen, struct Node **pRoot)
{
//检查边界条件
if(pPreOrder == NULL || pInOrder == NULL)
{
return;
}
//获得前序遍历的第一个节点
struct Node * pTemp = (struct Node *)malloc(sizeof(struct 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)
{
ReBuildTree(pPreOrder + 1, pInOrder, nLeftLen, &((*pRoot) -> pLeft));
}
//重建右子树
if(nRightLen > 0)
{
ReBuildTree(pPreOrder + nLeftLen + 1, pInOrder + nLeftLen + 1, nRightLen, &((*pRoot) -> pRight));
}
}
int main()
{
char szPreOrder[TREELEN] = {'a', 'b', 'd', 'c', 'e', 'f'};
char szInOrder[TREELEN] = {'d', 'b', 'a', 'e', 'c', 'f'};
struct Node * pRoot = NULL;
ReBuildTree(szPreOrder, szInOrder, TREELEN, &pRoot);
//printf("Hello world!\n");
return 0;
}