手工模拟过程:
1.由先序遍历序列知该序列的第一个元素为树根;
2.在中序遍历序列中找到根元素,则其左边为树根的左子树,其右边为树根的右子树;
3.在树根的左子树中进行步骤1和步骤2的分析;
4.在树根的右子树中进行步骤1和步骤2的分析。
显然这是一个递归处理的过程。具体实现如下:
#include <stdio.h>
void LastSearchOrder(char *pr,char *in,int length) {
if(!length) return ;
int RootPos = 0;
for(;RootPos<length;RootPos++) {
if(in[RootPos] == *pr) break;
}
LastSearchOrder(pr+1,in,RootPos);
LastSearchOrder(pr+1+RootPos,in+1+RootPos,length-RootPos-1);
printf("%c",*pr);
}
int main()
{
char* pr = "ABDECFG";
char* in = "DBEAFCG";
LastSearchOrder(pr,in,7);
return 0;
}
根据二叉树的前序遍历序列和中序遍历序列建树实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char elem;
struct TreeNode * left;
struct TreeNode * right;
}Node;
TreeNode* BuildTree(char *pr,char *in,int length) {
if(!length) return NULL ;
TreeNode * node = (TreeNode *)malloc(sizeof(TreeNode));
node->elem = *pr;
int RootPos = 0;
for(;RootPos<length;RootPos++) {
if(in[RootPos] == *pr) break;
}
node->left = BuildTree(pr+1,in,RootPos);
node->right = BuildTree(pr+1+RootPos,in+1+RootPos,length-RootPos-1);
printf("%c",*pr);
return node;
}
int main()
{
char* pr = "ABDECFG";
char* in = "DBEAFCG";
TreeNode * head = BuildTree(pr,in,7);
return 0;
}
参考:http://blog.csdn.net/feliciafay/article/details/6816871