1099 Build A Binary Search Tree (30 point(s))

题解

建树 and bfs。

#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
struct node {
	int v;
	int l, r;
};
vector<node> t;
vector<int> v;
int index, n;
void build(int u) {
	if(u == -1) return;
	build(t[u].l);
	t[u].v = v[index++];
	build(t[u].r);
} 
int main() {
	scanf("%d", &n);
	t.resize(n); v.resize(n);
	for(int i = 0; i < n; ++i) scanf("%d%d", &t[i].l, &t[i].r);
	for(int i = 0; i < n; ++i) scanf("%d", &v[i]);
	sort(v.begin(), v.end());
	build(0);
	printf("%d", t[0].v);
	queue<int> q;
	q.push(0); 
	while(!q.empty()) {
		int u = q.front(); q.pop();
		if(u) printf(" %d", t[u].v);
		if(t[u].l != -1) q.push(t[u].l);
		if(t[u].r != -1) q.push(t[u].r);
	}
	return 0;
}

 

相关文章:

  • 2021-04-15
  • 2022-12-23
  • 2021-07-20
  • 2021-08-29
  • 2022-01-15
  • 2022-03-02
  • 2022-12-23
  • 2021-05-19
猜你喜欢
  • 2022-12-23
  • 2021-11-30
  • 2021-09-04
  • 2022-12-23
  • 2021-08-19
  • 2021-07-22
  • 2022-12-23
相关资源
相似解决方案