重建二叉树
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1944
这道题是练习递归并深刻理解二叉树遍历的好题目(编程之美上也有)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
char chValue;
struct Node *lChild;
struct Node *rChild;
}Node;
//重建二叉树
void Rebuild(char *pPreOrder , char *pInOrder , Node **pRoot , int nTreeLen)
{
int nLeftLen , nRightLen;
char *pLeftEnd;
Node *p;
//边界条件检查
if(!pPreOrder || !pInOrder || !pRoot) return;
if(!(p = (Node *)malloc(sizeof(Node)))) return;
p->chValue = *pPreOrder;
p->lChild = p->rChild = NULL;
*pRoot = p;
if(nTreeLen == 1) return;
//划分左右子数
pLeftEnd = pInOrder;
while(*pLeftEnd != *pPreOrder) pLeftEnd++;
nLeftLen = (int)(pLeftEnd - pInOrder);
nRightLen = nTreeLen - nLeftLen - 1;
if(nLeftLen) Rebuild(pPreOrder + 1 , pInOrder , &(p->lChild) , nLeftLen);
if(nRightLen) Rebuild(pPreOrder + nLeftLen + 1, pInOrder + nLeftLen + 1 , &(p->rChild) , nRightLen);
}
//后序遍历
void PostOrder(Node *p)
{
if(p)
{
PostOrder(p->lChild);
PostOrder(p->rChild);
printf("%c",p->chValue);
}
}
int main(void)
{
char PreOrder[32] , InOrder[32];
Node *pTree;
//输入先序和中序序列
while(scanf("%s%s", PreOrder , InOrder) != EOF)
{
Rebuild(PreOrder , InOrder , &pTree , strlen(PreOrder));
PostOrder(pTree);
printf("\n");
}
return 0;
}