题目:由前序遍历和中序遍历重建二叉树
(前序序列:1 2 3 4 5 6 - 中序序列:3 2 4 1 6 5)
1.解题思路:
由前序遍历序列可知,第一个节点是根节点,
由中序遍历序列可知,第一个节点是根节点的左子树节点,
而且前序遍历中,根节点左边是左子树,右边是右子树
由上述分析结果,可以递归调用构建函数,根据左子树、右子树的先序、中序遍历重建左、右子树。
代码及注释如下
#include <stdlib.h>
#include <stdio.h>
typedef struct TNode
{
int value;
TNode* Lchild;
TNode* Rchild;
}TNode, *BTree;
BTree rebuild(int preOrder[], int startPre, int endPre, int inOrder[], int startIn, int endIn)
{
//先序遍历和中序遍历长度应相等,否则返回NULL
if (endPre - startPre != endIn - startIn) return NULL;
//起始位置不应大于末尾位置,否则返回NULL
if (startPre > endPre) return NULL;
//先序遍历的第一个元素为根节点
BTree tree = (BTree)malloc(sizeof(TNode));
tree->value = preOrder[startPre];
tree->Lchild = NULL;
tree->Rchild = NULL;
//先序遍历和中序遍历只有一个元素时,返回该节点
if (startPre == endPre) return tree;
//在中序遍历中找到根节点
int index, length;
for (index = startIn; index <= endIn; index++)
{
if (inOrder[index] == preOrder[startPre]) break;
}
//若未找到,返回空
if (index > endIn) return NULL;
//有左子树,递归调用构建左子树
if (index > startIn)
{
length = index - startIn;
tree->Lchild = rebuild(preOrder, startPre + 1, startPre + 1 + length - 1, inOrder, startIn, startIn + length - 1);
}
//有右子树,递归调用构建右子树
if (index < endIn)
{
length = endIn - index;
tree->Rchild = rebuild(preOrder, endPre - length + 1, endPre, inOrder, endIn - length + 1, endIn);
}
return tree;
}
//后序遍历二叉树
void postTraverse(BTree tree)
{
if (tree->Lchild != NULL) postTraverse(tree->Lchild);
if (tree->Rchild != NULL) postTraverse(tree->Rchild);
printf("%d ", tree->value);
}
int main()
{
int preOrder[] = { 1,2,4,5,3,6 };
int inOrder[] = { 4,2,5,1,6,3 };
BTree tree = rebuild(preOrder, 0, 5, inOrder, 0, 5);
postTraverse(tree);
printf("\n");
return 0;
}