题目: 已知二叉树 前序遍历 {1, 2, 4, 7, 3, 5, 6, 8} 中序遍历{4, 7, 2, 1, 5, 3, 6, 8};
重建二叉树。
树结点结构
typedef struct Node
{
int value;
struct Node *pLeft;
struct Node *pRight;
}Node;
思路: 前序遍历第一个结点一定为子树的根结点, 通过判断该结点在中序遍历中的位置来判断子树的左子树有几个结点,右子树有几个结点
比如: 前序遍历中的1为树的跟结点,找到1在中序遍历中的位置,可判断出根结点为1的树中,左子树有三个结点值(2 4 7),右子树有四个结点值(3 5 6 8)
对左子树与右子树分别进行递归运算
代码:
#include <iostream>
using namespace std;
#define M 8
typedef struct Node
{
int value;
struct Node *pLeft;
struct Node *pRight;
}Node;
Node * BuildTree(int *pre, int *mid, int len)
{
if (len == 0) // 表示无左子树或右子树了
{
return NULL;
}
int root = pre[0];
int i = 0; //判断左子树有几个结点 右子树有len-i-1个节点
while (pre[0] != mid[i])
{
i++;
}
Node *pNode = new Node;
pNode->value = root;
pNode->pLeft = BuildTree(pre+1, mid, i);
pNode->pRight = BuildTree(pre+i+1, mid+i+1, len-i-1);
return pNode;
}
void PrintfOut(Node *pHead)//后序遍历
{
if (pHead == NULL)
return;
else
{
PrintfOut(pHead->pLeft);
PrintfOut(pHead->pRight);
cout << pHead->value << " ";
}
}
int main()
{
int pre[M] = {1, 2, 4, 7, 3, 5, 6, 8};
int mid[M] = {4, 7, 2, 1, 5, 3, 6, 8};
Node *pHead = NULL;
pHead = BuildTree(pre, mid, M);
PrintfOut(pHead);
system("pause");
}