数据结构—前序和中序遍历的二叉树序列还原二叉树
代码:
#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;
}
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;
}
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";
bstTree* root = reStoreTree(pre, 0, 2, mid, 0, 2);
printf("前序遍历根据前序和中序构造的二叉树\n");
prePrint(root);
printf("\n");
system("pause");
return 0;
}
测试截图:
![请添加图片描述](https://i-blog.csdnimg.cn/blog_migrate/befd98322e99856fe565d92eaf1913f5.png)
时间复杂度O(logn),空间复杂度O(1)
如果存在什么问题,欢迎批评指正!谢谢!