1102 Invert a Binary Tree (25 分)
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.
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
作者
CHEN, Yue
单位
浙江大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
//1102 Invert a Binary Tree (25 分)
#include<bits/stdc++.h>
using namespace std;
int n;
const int MAX_N=22;
vector<int>tree[MAX_N];
bool havaFa[MAX_N];
void level(int root){
vector<int>levelArr;
queue<int>q;
q.push(root);
while(!q.empty()){
int fr= q.front();
q.pop();
levelArr.emplace_back(fr);
if(tree[fr].size()){
for(int i=tree[fr].size()-1;i>=0;i--){
int val=tree[fr][i];
if(val!=-1){
q.push(val);
}
}
// for(auto val: tree[fr]){
// q.push(val);
// }
}
}
int fir=1;
for(auto val:levelArr){
if(fir)fir=0;
else printf(" ");
printf("%d",val);
}
putchar('\n');
}
int inFir=1;
void in(int node){
if(node==-1)return;
// if(tree[node].size()>=2)
in(tree[node][1]);
if(inFir)inFir=0;
else printf(" ");
printf("%d",node);
// if(tree[node].size()>=1)
in(tree[node][0]);
}
int main(){
scanf("%d", &n);
getchar();
// printf("n: %d\n",n);
for(int i=0;i<n;i++){
char u,v;
scanf("%c %c",&u,&v);
getchar();
if(u!='-'){
tree[i].emplace_back(u-'0');
havaFa[u-'0']=1;
}else{
// 之前没有 写push -1, 样例2 错了
// 原因是 不写的话, 会把 - 1 和 1 - 当作同一种东西
tree[i].emplace_back(-1);
}
if(v!='-'){
tree[i].emplace_back(v-'0');
havaFa[v-'0']=1;
}else{
tree[i].emplace_back(-1);
}
}
int root=0;
for(int nodeNum=0;nodeNum<n;nodeNum++){
if(!havaFa[nodeNum]){
root=nodeNum;
break;
}
}
level(root);
in(root);
}