【PAT甲级】1099 Build A Binary Search Tree (30 分)

题意:

输入一个正整数N(<=100),接着输入N行每行包括0~N-1结点的左右子结点,接着输入一行N个数表示数的结点值。输出这颗二叉排序树的层次遍历。

AAAAAccepted code:

 1 #define HAVE_STRUCT_TIMESPEC
 2 #include<bits/stdc++.h>
 3 using namespace std;
 4 pair<int,int>a[107];
 5 int b[107];
 6 int cnt=0;
 7 int ans[107];
 8 void dfs(int x){
 9     if(x==-1)
10         return ;
11     dfs(a[x].first);
12     ans[x]=b[++cnt];
13     dfs(a[x].second);
14 }
15 void bfs(int x){
16     queue<int>q;
17     q.push(x);
18     while(!q.empty()){
19         int now=q.front();
20         q.pop();
21         if(a[now].first!=-1)
22             q.push(a[now].first);
23         if(a[now].second!=-1)
24             q.push(a[now].second);
25         if(now!=x)
26             cout<<" ";
27         cout<<ans[now];
28     }
29 }
30 int main(){
31     ios::sync_with_stdio(false);
32     cin.tie(NULL);
33     cout.tie(NULL);
34     int n;
35     cin>>n;
36     for(int i=1;i<=n;++i){
37         int x,y;
38         cin>>x>>y;
39         a[i-1]={x,y};
40     }
41     for(int i=1;i<=n;++i)
42         cin>>b[i];
43     sort(b+1,b+1+n);
44     dfs(0);
45     bfs(0);
46     return 0;
47 }

猜你喜欢

转载自www.cnblogs.com/ldudxy/p/11964473.html