A1102 Invert a Binary Tree (25point(s))
题意:
要求反转二叉树,输出层次和中序遍历
记录知识点:后序遍历可以反转二叉树。
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
#include"bits/stdc++.h"
using namespace std;
struct Node{
int l = -1;
int r = -1;
};
const int maxn = 20;
Node nodes[maxn];
int getNum(const string& s){
if(s[0] == '-')
return -1;
else
return stoi(s);
}
bool blank = false;
void layerOrder(int id){
queue<int> q;
q.push(id);
while(!q.empty()){
int t = q.front();
q.pop();
if(blank)
printf(" ");
else
blank = true;
printf("%d",t);
if(nodes[t].l != -1) q.push(nodes[t].l);
if(nodes[t].r != -1) q.push(nodes[t].r);
}
}
void inOrder(int id){
if(id == -1)
return;
inOrder(nodes[id].l);
if(blank)
printf(" ");
else
blank = true;
printf("%d",id);
inOrder(nodes[id].r);
}
void reverseTree(int id){
if(id == -1)
return;
reverseTree(nodes[id].l);
reverseTree(nodes[id].r);
swap(nodes[id].l,nodes[id].r);
}
int main(){
//freopen("input.txt","r",stdin);
int n; cin >> n;
map<int,int> notRoot;
for(int i=0;i<n;i++){
string s1,s2;
cin >> s1 >> s2;
int t1 = getNum(s1);
int t2 = getNum(s2);
nodes[i].l = t1; nodes[i].r = t2;
notRoot[t1] = 1; notRoot[t2] = 1;
}
int root;
for(int i=0;i<n;i++){
if(!notRoot[i]){
root = i;
break;
}
}
reverseTree(root);
layerOrder(root);
printf("\n"); blank = false;
inOrder(root);
}