/*重构二叉树的思想是先到后序遍历或者是先序遍历中先寻找根节点,然后在根据根据点的内容到中序遍历中找根节点的位置*/
#include<iostream>
#include<stdlib.h>
#include<queue>
using namespace std;
const int N = 35;
typedef struct node {
int data;
struct node *lchild, *right;
}node,*pnode;
void BFS(pnode root);
pnode create(int postL, int postR, int inL, int inR);
int post[N], in[N];//后序遍历和中序遍历
int main() {
int n = 0;
cin >> n;
for (int i = 0; i < 2*n; i++) {
if (i <= 6) cin >> post[i];
else cin >> in[i - 7];
}
pnode root = create(0, n - 1,0,n-1);
BFS(root);
system("pause");
return 0;
}
pnode create(int postL,int postR,int inL,int inR) {//递归还原二叉树
if (postL > postR) {
return NULL;
}
pnode root = (pnode)malloc(sizeof(node));
root->data = post[postR];//首先到后序遍历中找到跟节点
int k = 0;
while (in[k] != post[postR])k++;//找到根节点在中序遍历中的位置
int num = k - inL;//左子树规模
root->lchild = create(postL,postL+num-1,inL,k-1);//根据中序遍历得到的位置,左边为该根节点的左子树
root->right = create(postL+num,postR-1 ,k+1,inR);//中序遍历根节点的右边为其右子树
return root;
}
void BFS(pnode root) {
queue<pnode> q;
q.push(root);
while (!q.empty()) {
pnode tem = q.front();
printf("%d", tem->data);
if (tem!=q.back()) {
cout << " ";
}
q.pop();
if (tem->lchild != NULL)q.push(tem->lchild);
if (tem->right != NULL)q.push(tem->right);
}
cout << endl;
}
这段代码放到pat和牛客都会报段错误和程序内存过大的问题,
定位到:
for (int i = 0; i < 2*n; i++) {
if (i <= 6) cin >> post[i];
else cin >> in[i - 7];
}
这个循环这里,我只是想用一个循环输入两个而已,然后就报错了,换成两个循环就能够通过了