解题思路:
1) 通过前序遍历和中序遍历结果重建二叉树
2)后序遍历二叉树
关键点:
中序遍历的特点是先遍历左子树,接着根节点,然后遍历右子树。这样根节点就把左右子树隔开了。
而前序遍历的特点是先访问根节点,从而实现前序遍历结果提供根节点信息,中序遍历提供左右子树信息,从而实现二叉树的重建。
上代码:
#include "stdafx.h"
#include "string.h"
#include "stdio.h"
//前序遍历结果:ABDCEF
//后序遍历结果:DBAECF
//后序遍历结果:DBEFCA
struct Node
{
char ch;
Node* pLeft;
Node* pRight;
} SNode;
void RebuildTree(char* preOrder, char* midOrder, int len, Node** node)
{
if(preOrder == NULL || midOrder == NULL || len == 0)
return;
*node = new Node;
(*node)->ch = preOrder[0];
(*node)->pLeft = NULL;
(*node)->pRight = NULL;
char* pChildRoot = strchr(midOrder, preOrder[0]);
if(pChildRoot != NULL)
{
int nLeftChildLen = pChildRoot - midOrder;
RebuildTree(preOrder+1, midOrder, nLeftChildLen, &(*node)->pLeft);
RebuildTree(preOrder+nLeftChildLen+1, midOrder+nLeftChildLen+1, len-nLeftChildLen-1, &(*node)->pRight);
}
}
void PostMapping(Node* root)
{
if( root == NULL )
return;
PostMapping(root->pLeft);
PostMapping(root->pRight);
printf(" %c", root->ch);
}
int main(int argc, char* argv[])
{
char PreOrder[] = "ABDCEF";
char MidOrder[] = "DBAECF";
Node* root;
RebuildTree(PreOrder, MidOrder, strlen(PreOrder), &root);
PostMapping(root);
return 0;
}