题目大意:
给定中序和先序,输出left-view,其实就是输出层序遍历,每层输出一个即可。类似题目:A1020
思路:
①构建树;
②层序遍历树。
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 25;
int in[maxn], pre[maxn];
struct node {
int data;
int layer;
node* lchild;
node* rchild;
};
node* create(int preL, int preR, int inL, int inR) {
if (preL > preR)
return NULL;
node* root = new node;
root->data = pre[preL];
int k;
for (k = inL; k <= inR; k++) {
if (in[k] == root->data)
break;
}
int numLeft = k - inL;
root->lchild = create(preL+1, preL + numLeft, inL, k - 1);
root->rchild = create(preL + numLeft + 1, preR, k + 1, inR);
return root;
}
bool hashTable[maxn] = { false };// 判断该层结点有没被输出过,这样可以保证一层只输出一个结点
void BFS(node* root) {
queue<node*> q;
root->layer = 1;
q.push(root);
while (!q.empty()) {
node* now = q.front();
q.pop();
int lay = now->layer;
if (hashTable[lay] == false) {
printf("%d", now->data);
hashTable[lay] = true;
}
if (now->lchild) {
now->lchild->layer = now->layer + 1;
q.push(now->lchild);
}
if (now->rchild) {
now->rchild->layer = now->layer + 1;
q.push(now->rchild);
}
}
}
int main() {
freopen("input.txt", "r", stdin);
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &pre[i]);
}
node* root = create(0, n - 1, 0, n - 1);
BFS(root);
return 0;
}