数据结构—后序和中序遍历的二叉树序列还原二叉树
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct bstTree {
char data;
struct bstTree* lchild, *rchild;
}bstTree;
bstTree * reStoreTree(char* pre, int preSt, int preEnd, char *mid, int midSt, int midEnd) {//通过前序和中序二叉树遍历还原树
if (preSt > preEnd) {
return NULL;//如果找不到左子树了则返回NULL
}
char rs = pre[preSt];
int j;
for (j = midSt; j <= midEnd; j++) {
if (rs == mid[j]) {
break;//在中序序列中找到当前的根节点
}
}
if (j > midEnd) {
printf("中序序列有误!\n");
return NULL;//不再进行下面子树的操作
}
int gapLength = j - midSt;//左右子树跟结点的寻找范围
bstTree* root = (bstTree*)malloc(sizeof(bstTree));
root->data = rs;
root->lchild = reStoreTree(pre, preSt + 1, preSt + gapLength, mid, midSt, j - 1);
root->rchild = reStoreTree(pre, preSt + gapLength + 1, preEnd, mid, j + 1, midEnd);
return root;
}
bstTree * reStoreTree1(char* last, int lastSt, int lastEnd, char *mid, int midSt, int midEnd) {//通过前序和中序二叉树遍历还原树
if (lastSt > lastEnd) {
return NULL;//如果找不到左子树了则返回NULL
}
char rs = last[lastEnd];
int j;
for (j = midSt; j <= midEnd; j++) {
if (rs == mid[j]) {
break;//在中序序列中找到当前的根节点
}
}
if (j > midEnd) {
printf("中序序列有误!\n");
return NULL;//不再进行下面子树的操作
}
int gapLength = j - midSt;//左右子树跟结点的寻找范围
bstTree* root = (bstTree*)malloc(sizeof(bstTree));
root->data = rs;
root->lchild = reStoreTree(last, lastSt, lastEnd - gapLength-1, mid, midSt, j - 1);
root->rchild = reStoreTree(last, lastEnd - gapLength, lastEnd-1, mid, j + 1, midEnd);
return root;
}
void prePrint(bstTree* BSTTree) {//前序遍历二叉树
if (BSTTree) {
printf("%c ", BSTTree->data);
prePrint(BSTTree->lchild);
prePrint(BSTTree->rchild);
}
}
int main() {
char pre[4] = "ABC";
char mid[4] = "BAC";
char last[4] = "BCA";
//bstTree* root = reStoreTree(pre, 0, 2, mid, 0, 2);//根据前序和中序构造的二叉树
bstTree* root = reStoreTree1(last, 0, 2, mid, 0, 2);//根据后序和中序构造的二叉树
printf("前序遍历根据后序和中序构造的二叉树\n");
prePrint(root);//前序遍历二叉树
printf("\n");
system("pause");
return 0;
}
测试截图:
时间复杂度O(n),空间复杂度O(logn)
c语言字符串的学习参考链接:https://blog.csdn.net/beyond_yourself/article/details/108889618