当前位置:网站首页>1099 establish binary search tree (30 points)

1099 establish binary search tree (30 points)

2022-04-23 08:41:00 Huaihua second affectionate

Binary search tree (BST) Defined recursively as a binary tree with the following properties :
  • The left subtree of a node contains only nodes whose key is less than the node key .
  • The right subtree of a node contains only nodes whose key is greater than or equal to the node key .
  • The left and right subtrees must also be binary search trees .

Given the structure of a binary tree and a series of different integer keys , There is only one way to populate these keys into the tree , So that the generated tree can meet BST The definition of . You should output the level order traversal sequence of the tree . chart 1 Sum graph 2 This example is illustrated .

Enter specifications :

Each input file contains a test case . For each case , The first line gives a positive integer N (≤100), This is the total number of nodes in the tree . next N Each row contains the left and right children of a node , The format is , The premise is that the node number is from 0 To left_index right_indexN−1,0 Always the root . If a child is missing , that −1 Will represent NULL Sub pointer . Last N Different integer keys are given on the last line .

Output specifications :

For each test case , Print the level order traversal sequence of the tree in one line . All numbers must be separated by spaces , There can't be extra spaces at the end of the line .

Sample input :

<span style="color:#404040"><span style="background-color:#ffffff"><code class="language-in">9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42
</code></span></span>

Sample output :

58 25 82 11 38 67 45 73 42

#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;

typedef long long ll;

const int N = 1e5+10;
map<int,int>l,r;
int kp[10010];
int res[10010];
int u=0;
void dfs(int t){
	if(l[t]!=-1)dfs(l[t]);// The smallest arrangement is on the left 
	res[t]=kp[u++];// This is almost the median 
	if(r[t]!=-1)dfs(r[t]);
	
}
void print(){
	queue<int>p;
	p.push(0);
	int num=0;
	while(p.size()){
		int t=p.front();
		if(!num++)cout<<res[t];
		else cout<<' '<<res[t];
		p.pop();
		if(l.count(t)&&l[t]!=-1)p.push(l[t]);
		if(r.count(t)&&r[t]!=-1)p.push(r[t]);
	}
}
int main(){
	int n;
	cin>>n;
	int x,y;
	for(int i=0;i<n;i++){
		cin>>x>>y;
		l[i]=x;
		r[i]=y;
	}
	for(int i=0;i<n;i++){
		cin>>kp[i];
	}
	sort(kp,kp+n);
	dfs(0);
	print();
	return 0;
}

版权声明
本文为[Huaihua second affectionate]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230835222858.html