已知中序和后序求层次遍历
题目
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <time.h>
#include <stack>
#include <queue>
#include <string.h>
#include <cmath>
#include <bitset>
#include <set>
#include <map>
#define ll long long
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
const ll ds = 1e15+7;
const double p = 3.141592653589793238462643383;
using namespace std;
struct node{
int x;
node *l,*r;
};
node* build(int post[],int in[],int n)
{
int k = 0;
if(n <= 0) return NULL;
node *root = (struct node*)malloc(sizeof(struct node));
int val = post[n-1];
root -> x = post[n-1];
for(int i = 0; i < n; i++){
if(in[i] == val){
k = i;
break;
}
}
root -> l = build(post,in,k);
root -> r = build(post+k,in+k+1,n-k-1);
}
queue<node*>q;
int a[1005],t = 0;
void bfs(node *root)
{
q.push(root);
while(!q.empty()){
node *s = q.front();
q.pop();
a[t++] = s->x;
if(s->l) q.push(s->l);
if(s->r) q.push(s->r);
}
}
int main()
{
int n,post[1005],in[1005];
scanf("%d",&n);
for(int i = 0; i < n; i++) scanf("%d",&post[i]);
for(int i = 0; i < n; i++) scanf("%d",&in[i]);
node *root = build(post,in,n);
bfs(root);
for(int i = 0; i < t; i++){
if(i == 0) printf("%d",a[i]);
else printf(" %d",a[i]);
}
return 0;
}
已知前序后序求层次遍历(包括子女交换)
题目
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <time.h>
#include <stack>
#include <queue>
#include <string.h>
#include <cmath>
#include <bitset>
#include <set>
#include <map>
#define ll long long
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
const ll ds = 1e15+7;
const double p = 3.141592653589793238462643383;
using namespace std;
int N;
int pre[1005],in[1005];
struct node{
int x;
node *l,*r;
};
void build(int L,int R,int &n,node* &root)
{
int k = 0,flag = -1;
for(int i = L; i <= R; i++){
if(in[i] == pre[n]){
flag = i;
break;
}
}
if(flag == -1) return;
node *t = (struct node*)malloc(sizeof(struct node));
t -> l = NULL;
t -> r = NULL;
t -> x = in[flag];
root = t;
n++;
if(flag > L) build(L,flag-1,n,root->l);
if(flag < R) build(flag+1,R,n,root->r);
}
queue<node*>q;
int a[1005],t = 0;
void bfs(node *root)
{
q.push(root);
while(!q.empty()){
node *s = q.front();
q.pop();
a[t++] = s->x;
if(s->l) q.push(s->l);
if(s->r) q.push(s->r);
}
}
void temp(node *root)
{
if(root){
node *t = root -> l;
root -> l = root -> r;
root -> r = t;
temp(root->l);
temp(root->r);
}
}
int main()
{
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 = (struct node*)malloc(sizeof(struct node));
int t = 0;
build(0,N-1,t,root);
temp(root);
bfs(root);
for(int i = 0; i < t; i++){
if(i == 0) printf("%d",a[i]);
else printf(" %d",a[i]);
}
return 0;
}