# 1102. Invert a Binary Tree (25)

400 ms

65536 kB

16000 B

Standard

CHEN, Yue

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

#### c++代码：

#include<bits/stdc++.h>
using namespace std;
struct Node{//结点类，没有数据域
int left=-1,right=-1;
};
Node tree[10];
void inOrder(int root,bool&space){//中根遍历，space指示输出数字之前是否需要输出空格
if(root==-1)//root==-1,直接返回
return;
inOrder(tree[root].left,space);//递归遍历左子树
printf("%s%d",space?" ":"",root);//输出
space=true;//已经输出过，以后都需要输出空格，置false为true
inOrder(tree[root].right,space);//递归遍历右子树
}
void levelOrder(int root){//层次遍历
queue<int>q;
q.push(root);
while(!q.empty()){
int t=q.front();
q.pop();
printf("%s%d",t==root?"":" ",t);//不是根节点的输出前都需输出一个空格
if(tree[t].left!=-1)
q.push(tree[t].left);
if(tree[t].right!=-1)
q.push(tree[t].right);
}
}
int main(){
int N;
scanf("%d",&N);
bool child[N]={false};
for(int i=0;i<N;++i){
char a,b;
scanf("\n%c %c",&a,&b);
if(a!='-'){
tree[i].right=a-'0';
child[a-'0']=true;
}
if(b!='-'){
tree[i].left=b-'0';
child[b-'0']=true;
}
}
int root=find(child,child+N,false)-child;//仍为false的下标为根节点标号
levelOrder(root);
printf("\n");
bool space=false;
inOrder(root,space);
return 0;
}


• 擅长领域：
• 算法