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 N1. Then N lines follow, each corresponds to a node from 0 to N1, 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
 
 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <set>
 4 #include <string.h>
 5 #include <vector>
 6 #include <queue>
 7 using namespace std;
 8 struct node{
 9     int data;
10     int l=-1,r=-1;
11 };
12 const int maxn = 11;
13 int n;
14 node tree[maxn];
15 int vis[maxn]={0};
16 void lvl(int root){
17     queue<int> q;
18     q.push(root);
19     int cnt=0;
20     while(!q.empty()){
21         int now=q.front();
22         q.pop();
23         cnt++;
24         if(cnt<n)printf("%d ",now);
25         else printf("%d\n",now);
26         if(tree[now].r!=-1)q.push(tree[now].r);
27         if(tree[now].l!=-1)q.push(tree[now].l);
28     }
29 }
30 int cnt=0;
31 void ino(int root){
32     if(root==-1)return;
33     if(tree[root].r!=-1) ino(tree[root].r);
34     cnt++;
35     if(cnt<n)printf("%d ",root);
36     else printf("%d",root);
37     if(tree[root].l!=-1) ino(tree[root].l);
38 }
39 int main(){
40     scanf("%d",&n);
41     getchar();
42     for(int i=0;i<n;i++){
43         char c1,c2;
44         scanf("%c %c",&c1,&c2);
45         getchar();
46         int l=-1,r=-1;
47         if(c1!='-'){
48             l=c1-'0';
49             vis[l]=1;
50         }
51         if(c2!='-'){
52             r=c2-'0';
53             vis[r]=1;
54         }
55         tree[i].l=l;
56         tree[i].r=r;
57         tree[i].data=i;
58         
59     }
60     int root;
61     for(int i=0;i<n;i++){
62         if(vis[i]==0){
63             root=i;
64             break;
65         }
66     }
67     lvl(root);
68     ino(root);
69 }
View Code

注意点:又是读字符出现了错误,注意换行符一定要用getchar吃掉,不然会被%c认为是输入字符。别的就是普通的树的遍历