题意:
输入一个正整数N(<=10),接着输入0~N-1每个结点的左右儿子结点,输出这颗二叉树的反转的层次遍历和中序遍历。
AAAAAccepted code:
1 #define HAVE_STRUCT_TIMESPEC 2 #include<bits/stdc++.h> 3 using namespace std; 4 int a[17][5]; 5 bool vis[15]; 6 void bfs(int r){ 7 queue<int>q; 8 q.push(r); 9 cout<<r; 10 while(!q.empty()){ 11 int now=q.front(); 12 q.pop(); 13 if(a[now][0]!=-1){ 14 cout<<" "; 15 cout<<a[now][0]; 16 q.push(a[now][0]); 17 } 18 if(a[now][1]!=-1){ 19 cout<<" "; 20 cout<<a[now][1]; 21 q.push(a[now][1]); 22 } 23 } 24 } 25 int flag=0; 26 void dfs(int r){ 27 if(a[r][0]!=-1) 28 dfs(a[r][0]); 29 if(flag) 30 cout<<" "; 31 cout<<r; 32 flag=1; 33 if(a[r][1]!=-1) 34 dfs(a[r][1]); 35 } 36 int main(){ 37 ios::sync_with_stdio(false); 38 cin.tie(NULL); 39 cout.tie(NULL); 40 for(int i=0;i<10;++i) 41 a[i][0]=a[i][1]=-1; 42 int n; 43 cin>>n; 44 for(int i=0;i<n;++i){ 45 char x; 46 cin.ignore(); 47 cin>>x; 48 cin.ignore(); 49 if(x!='-') 50 a[i][1]=x-'0',vis[x-'0']=1; 51 char y; 52 cin>>y; 53 if(y!='-') 54 a[i][0]=y-'0',vis[y-'0']=1; 55 } 56 int root=0; 57 for(int i=0;i<n;++i) 58 if(!vis[i]) 59 root=i; 60 bfs(root); 61 cout<<"\n"; 62 dfs(root); 63 return 0; 64 }