#include<iostream>
using namespace std;
struct BiNode
{
int value;
BiNode * lchild;
BiNode * rchild;
}node;
typedef BiNode *Btree;
//参数代表遍历子树的起始位置
Btree rebuild(int preOrder[], int startpre, int endpre, int inOrder[], int startin, int endin)
{
//前序和中序两者长度应该相等
if (endpre - startpre != endin - startin) return NULL;
if (startpre - endpre > 0) return NULL;
Btree tree = new BiNode;
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;
}
//index代表中遍历中根节点的下标,若index>startin,则代表有左子树,递归调用构建左子树
if (index > startin)
{
//现在length代表了左子树结点的个数
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);
cout << 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);
return 0;
}
其实根据前序和中序的特点就可以做了,前序的第一个元素必定是根节点,那么在中序的序列中查找这个根节点的位置,两侧分为两部分,递归下去即可。
使用前序和中序遍历重构二叉树
最新推荐文章于 2024-11-28 16:49:07 发布