原题:https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
题目要求很简单,就是已知二叉树后序/中序,求层序
我首先重建了这颗二叉树,然后进行层序遍历。
我熟悉了二叉树的指针操作,还有就是建议做题之前自己在纸上模拟一下:
#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>
//new and delete
//A1020 Tree Traversals
using namespace std;
const int MaxN = 40;
typedef int ElemType;
struct node {
ElemType v;
node* lchild;
node* rchild;
};
int post[MaxN],in[MaxN]; //后序(左右根)、中序(左根右)遍历
//当前后序遍历[postL, postR], 当前中序遍历[inL, inR],返回根节点地址
node* create_po_in(int postL, int postR, int inL, int inR) {
//退出条件
if (postL > postR)
return NULL;
int root1 = post[postR];
//寻找in[k]=root1
int k = -1;
for (k = inL; k <= inR; k++) {
if (in[k] == root1)
break;
}
if (k == -1) {
cout << "error!" << endl;
return NULL;
}
node* root=new node;
root->v = root1;
root->lchild = create_po_in(postL, postL + k - 1-inL, inL, k - 1);
root->rchild = create_po_in(postL + k-inL, postR - 1, k + 1, inR);
return root;
}
//层序遍历
void LevelOrder(node* root,int N) {
queue<node*>q;
q.push(root);
int index=0;
while (!q.empty()) {
//访问队首元素
node* temp = q.front();
cout << temp->v;
index++;
if (index < N)
cout << " ";
else
cout << endl;
q.pop();
//左右孩子入队
if(temp->lchild)
q.push(temp->lchild);
if (temp->rchild)
q.push(temp->rchild);
}
return;
}
int main() {
int N; //The number of node
cin >> N;
for (int j = 0; j < N; j++) {
cin >> post[j];
}
for (int j = 0; j < N; j++) {
cin >> in[j];
}
node* root = create_po_in(0, N - 1, 0, N - 1);
LevelOrder(root,N);
return 0;
}