PTA天梯赛 玩转二叉树|中序前序建树 层序遍历 镜像反转

思路

1.中序遍历和前序遍历
2.镜像反转,就是交换左右子节点
3.bfs层序遍历

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e3;
int in[maxn],pre[maxn];
int n;
struct node{
	int v;
	node *l,*r;
};
vector<int> ans;

//1.中序遍历和前序遍历
node *build(int index,int inl,int inr){
	if(inr < inl) return NULL;
	int pos = inl;
	while(in[pos] != pre[index]) pos++;
	node *root = new node();
	root->l = NULL,root->r = NULL,root->v = pre[index];
	root->l = build(index+1,inl,pos-1);
	root->r = build(index+pos-inl+1,pos+1,inr);
	return root;
}

//2.镜像反转,就是交换左右子节点
void dfs(node *root){
	if(root->l != NULL && root->r != NULL){
		swap(root->l,root->r);
	}
	if(root->l != NULL) dfs(root->l);
	if(root->r != NULL) dfs(root->r);
}

//3.bfs层序遍历
void bfs(node *root){
	queue<node> q;
	q.push(*root);
	while(!q.empty()){
		node u = q.front();
		q.pop();
		ans.push_back(u.v);
		if(u.l != NULL) q.push(*u.l);
		if(u.r != NULL) q.push(*u.r);
	}
}

int main(){
	cin>>n;
	for(int i=1;i<=n;i++) cin>>in[i];
	for(int i=1;i<=n;i++) cin>>pre[i];
	node* Root= new node();
	Root->l = NULL,Root->r = NULL,Root->v = in[1];
	Root = build(1,1,n);
	dfs(Root);
	bfs(Root);
	for(int i=0;i<ans.size()-1;i++){
		cout<<ans[i]<<" ";
	}
	cout<<ans[ans.size()-1];
	return 0;
}
posted @ 2020-04-02 22:48  fishers  阅读(265)  评论(0编辑  收藏  举报