数据结构 --- 二叉树(遍历)

中序+后序转层序

void levelorder(int post_root,int inL,int inR,int idx){
	//边界:inL>inR 不要写成inL>=inR 
	if(inL > inR) return ;
	level.push_back({post[post_root],idx});
	int k;
	for(k = inL; k <= inR; k ++ ){
		if(in[k] == post[post_root]) break;
	}
	levelorder(post_root - 1 - (inR - k),inL,k - 1,2 * idx);
	levelorder(post_root - 1,k + 1,inR,2 * idx + 1);
}

bool cmp(Node a,Node b){
	return a.idx < b.idx;
}
levelorder(n - 1,0,n - 1,1);
sort(level.begin(),level.end(),cmp);

中序+后序转先序

void preorder(int post_root,int inL,int inR){
	//边界:inL>inR 不要写成inL>=inR 
	if(inL > inR) return ;
	pre.push_back({post[post_root],idx});
	int k;
	for(k = inL; k <= inR; k ++ ){
		if(in[k] == post[post_root]) break;
	}
	levelorder(post_root - 1 - (inR - k),inL,k - 1);
	levelorder(post_root - 1,k + 1,inR);
}
preorder(n - 1,0,n - 1);
sort(level.begin(),level.end(),cmp);

1020 Tree Traversals (25分)

#include<bits/stdc++.h>

using namespace std;

#define  mm(a,x) memset(a,x,sizeof a)
#define  mk make_pair
#define ll long long
#define pii pair<int,int>
#define inf 0x3f3f3f3f
#define lowbit(x) (x) & (-x)
#define endl "\n"

const int N = 40;

struct Node{
	int data,idx;
};

int n;
int in[N],post[N];
vector<Node > level;

/*
中序:左根右
后序:左右根

层序:从根结点开始一层层遍历
 
*/

void levelorder(int post_root,int inL,int inR,int idx){
	//边界:inL>inR 不要写成inL>=inR 
	if(inL > inR) return ;
	level.push_back({post[post_root],idx});
	int k;
	for(k = inL; k <= inR; k ++ ){
		if(in[k] == post[post_root]) break;
	}
	levelorder(post_root - 1 - (inR - k),inL,k - 1,2 * idx);
	levelorder(post_root - 1,k + 1,inR,2 * idx + 1);
}

bool cmp(Node a,Node b){
	return a.idx < b.idx;
}
int main() {
	cin >> n;
	for(int i = 0; i < n; i ++ ) cin >> post[i];
	for(int i = 0; i < n; i ++ ) cin >> in[i];
	levelorder(n - 1,0,n - 1,1);
	sort(level.begin(),level.end(),cmp);
	for(int i = 0; i < n; i ++ ){
		if(i) cout<<" ";
		cout<<level[i].data;
	}
	return 0;
}
posted @ 2020-11-26 20:14  chstor  阅读(52)  评论(0编辑  收藏  举报