noj 18 根据二叉树的前序和中序遍历结果重建二叉树
重构的原理:
(参考链接:https://blog.csdn.net/okiwilldoit/article/details/78355872)
下面放重建函数的递归代码
void InitNode(p_BTNode* p) {
*p = (p_BTNode)malloc(sizeof(BTNode));
(*p)->Lchild = (*p)->Rchild = NULL;
}
p_BTNode Rebuild(char* str_pre, char* str_in) {//分别是前序字符串,中序字符串,右字串长度
char c1 = str_pre[0], c2 = str_in[0];
char s1[100] = { 0 }, s2[100] = { 0 };
int Lcounter = 0, Rcounter = 0;
while (c2 != c1) {//这一个循环有两个作用,统计左串长度以及生成新的左串
s1[Lcounter] = c2;
c2 = str_in[++Lcounter];
}
c2 = str_in[Lcounter + 1];
while (c2 != 0) {//同上
s2[Rcounter] = c2;
c2 = str_in[++Rcounter + Lcounter + 1];
}
p_BTNode p;
InitNode(&p);
p->data = c1;
if (Lcounter == 0) {
p->Lchild = NULL;//递归出口
}
else {
p->Lchild = Rebuild(str_pre + 1, s1);
}
if (Rcounter == 0) {
p->Rchild = NULL;//递归出口
}
else {
p->Rchild = Rebuild(str_pre + Lcounter + 1, s2);
}
return p;
}
整体代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
char data;
struct Node* Lchild;
struct Node* Rchild;
}BTNode, * p_BTNode;
void InitNode(p_BTNode* p) {
*p = (p_BTNode)malloc(sizeof(BTNode));
(*p)->Lchild = (*p)->Rchild = NULL;
}
p_BTNode Rebuild(char* str_pre, char* str_in) {//分别是前序字符串,中序字符串,右字串长度
char c1 = str_pre[0], c2 = str_in[0];
char s1[100] = { 0 }, s2[100] = { 0 };
int Lcounter = 0, Rcounter = 0;
while (c2 != c1) {//这一个循环有两个作用,统计左串长度以及生成新的左串
s1[Lcounter] = c2;
c2 = str_in[++Lcounter];
}
c2 = str_in[Lcounter + 1];
while (c2 != 0) {//同上
s2[Rcounter] = c2;
c2 = str_in[++Rcounter + Lcounter + 1];
}
p_BTNode p;
InitNode(&p);
p->data = c1;
if (Lcounter == 0) {
p->Lchild = NULL;//递归出口
}
else {
p->Lchild = Rebuild(str_pre + 1, s1);
}
if (Rcounter == 0) {
p->Rchild = NULL;//递归出口
}
else {
p->Rchild = Rebuild(str_pre + Lcounter + 1, s2);
}
return p;
}
void PostOrder(p_BTNode root) {
if (root->Lchild)
PostOrder(root->Lchild);
if (root->Rchild)
PostOrder(root->Rchild);
printf("%c", root->data);
}
int main() {
p_BTNode p;
InitNode(&p);
char s1[100] = { 0 }, s2[100] = { 0 };
scanf("%s", s1);
scanf("%s", s2);
p = Rebuild(s1, s2);
PostOrder(p);
return 0;
}