A1102 Invert a Binary Tree

The following is from Max Howell @twitter:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
Now it’s your turn to prove that YOU CAN invert a binary tree!

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.

Output Specification:
For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

1
2
3
4
5
6
7
8
9
10
11
12
13
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

题目要求输出反转后的二叉树层序和终须遍历序列

由于给的是节点编号 所以用二叉树的静态写法更方便

在后序遍历访问到根节点时 交换它的左右孩子 即可反转二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<bits/stdc++.h> 
#define MAX 12
using namespace std;
typedef long long ll;

int N,sum=0,num=0;
int notR[MAX];
struct node
{
int left;
int right;

};
node nodes[MAX];
void bfs(int root){
queue<int> que;
que.push(root);
while(!que.empty()){
int t=que.front();
cout<<t;
que.pop();
num++;
if(num<N) cout<<" ";
if(nodes[t].left!=-1) que.push(nodes[t].left);
if(nodes[t].right!=-1) que.push(nodes[t].right);
}

}
void porder(int root){
if(root==-1) return;
porder(nodes[root].left);
porder(nodes[root].right);
swap(nodes[root].left,nodes[root].right);
}
void inorder(int root){
if(root==-1) return;
inorder(nodes[root].left);
cout<<root;
sum++;
if(sum<N) cout<<" ";
inorder(nodes[root].right);
}
int strto(char a){
if(a=='-') return -1;
else {
int b=a-'0';
notR[b]=true;//!
return b;
}
}
int findR(){
int i=-1;
for(i=0;i<N;i++){
if(notR[i]==false){
break;
}
}
return i;
}
int main(){
cin>>N;
for(int i=0;i<N;i++){
char a,b;
getchar();
scanf("%c %c",&a,&b);
int l=strto(a);
int r=strto(b);
nodes[i].left=l;nodes[i].right=r;
}
int root=findR();
porder(root);
bfs(root);
cout<<endl;
inorder(root);



}