根据前序遍历和中序遍历结果重建二叉树(递归方法)
假设已经有了前序遍历和中序遍历的结果,如何重建这棵树呢?
给定函数定义如下:
void Rebuild(char* pPreOrder, //前序遍历结果
char* pInOrder, //中序遍历结果
int nTreeLen, //树的长度
NODE** pRoot) //返回NODE**类型
用递归的方法解法如下:
#include <iostream>
using namespace std;
struct NODE{
NODE* pLeft;
NODE* pRight;
char chValue;
};
int GetPos(char* str, char ch)
{
for(int i=0; i<strlen(str); i++)
{
if(ch==str[i])
{
return i;
}
}
return -1;
}
void Rebuild(char* pPreOrder, char* pInOrder, int nTreeLen, NODE** pRoot)
{
if(*pRoot==NULL)
return;
*pRoot=(NODE*)malloc(sizeof(NODE));
(*pRoot)->chValue = pPreOrder[0];
int i=GetPos(pInOrder, pPreOrder[0]);
if(i>=nTreeLen-1)
(*pRoot)->pRight=NULL;
if(i==0)
(*pRoot)->pLeft=NULL;
Rebuild(&pPreOrder[1], pInOrder, i, &(*pRoot)->pLeft);
Rebuild(&pPreOrder[i+1], &pInOrder[i+1],nTreeLen-i-1, &(*pRoot)->pRight);
}
调用示例:
void PostOrderRetrieval(NODE* root) //后序遍历树
{
if(root==NULL)
return;
if(root->pLeft !=NULL)
PostOrderRetrieval(root->pLeft);
if(root->pRight !=NULL)
PostOrderRetrieval(root->pRight);
printf("%c\n", root->chValue);
}
int main()
{
NODE** root;
root = (NODE**)malloc(sizeof(NODE*));
Rebuild("abdehcfgij", "dbheafcgji", 10, root);
PostOrderRetrieval(*root);
free(*root);
free(root);
}
posted on 2011-09-06 20:56 Lovell Liu 阅读(1733) 评论(0) 编辑 收藏 举报