L2-011 Play with binary tree (build tree + BFS)

topic link

https://pintia.cn/problem-sets/994805046380707840/problems/994805065406070784

ideas

Since the middle root traversal and the first root traversal are given, we first locate the root node of the tree through the first root traversal, then divide the binary tree through the middle root traversal, and then continue to recursively process the left and right subtrees from left to right, and finally establish this After a binary tree, we BFSput the right subtree into the queue first, so that we can achieve the level-order traversal of mirror inversion. For details, please see the code

code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f

const int N = 1e2+10;

int in[N],pre[N],n;

struct Node{
    
    
	int l,r;
}Tree[N];

int build(int l1,int r1,int l2,int r2){
    
    //l1-r1中序遍历,l2-r2先序遍历
	if(l1 > r1 || l2 > r2) return 0;
	int p = l1;
	while(in[p] != pre[l2]) p++;
	int len = p - l1;
	int rt = pre[l2];
	Tree[rt].l = build(l1,p-1,l2+1,l2 + len);
	Tree[rt].r = build(p+1,r1,l2+len+1,r2);
	return rt;
}

void bfs(int s){
    
    
	queue<int> que;
	que.push(s);
	int cnt = 0;
	while(!que.empty()){
    
    
		int rt = que.front();
		que.pop();
		cout<<rt<<" \n"[++cnt==n];
		int l = Tree[rt].l,r = Tree[rt].r;
		if(r) que.push(r);
		if(l) que.push(l);
	}
}


int main()
{
    
    
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n;
	for(int i = 1;i <= n; ++i) cin>>in[i];
	for(int i = 1;i <= n; ++i) cin>>pre[i];
	
	build(1,n,1,n);
	bfs(pre[1]);
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_46201544/article/details/123936760