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
解题思路:题目给出的输入数据是每个节点的左右孩子信息,即节点0的左右孩子分别为节点1与空,节点1没有左右孩子,节点2左右孩子分别为节点0与空,以此类推。此题给出了左右节点的信息,所以用静态链表做比较方便。对二叉树进行反转不需要真正反转,只要将中序遍历的顺序变为(右中左即可),层序遍历每次先将右孩子进队。对于根节点寻找方法,输入数据中没有的数字就是根节点。题目要求结尾没有空格,所以用flag标志来控制输出,只有第一个数据是直接输出,其他都是先输出空格再输出数据。
#include<cstdio>
#include<queue>
#include<string>
#include<iostream>
using namespace std;
struct node{
int data;
int lchild;
int rchild;
}Node[20];
int flag = 0;
void layerorder(int root){ //层序遍历
queue<int> q;
q.push(root);
while(!q.empty()){
int front = q.front();
q.pop();
if(flag)
printf(" ");
printf("%d",Node[front].data);
flag = 1;
if(Node[front].rchild!=-1) q.push(Node[front].rchild); //先右子树
if(Node[front].lchild!=-1) q.push(Node[front].lchild); //后左子树
}
}
void inorder(int root){
if(root == -1)
return;
inorder(Node[root].rchild);
if(flag)
printf(" ");
printf("%d",Node[root].data);
flag = 1;
inorder(Node[root].lchild);
}
int hashtable[20] = {0};
int main(void){
int N;
scanf("%d",&N);
string temp;
for(int i = 0;i < N;i++){
Node[i].data = i;
cin>>temp;
if(temp[0]>='0'&&temp[0]<='9'){
Node[i].lchild = temp[0] - '0';
hashtable[temp[0] - '0'] = 1;
}
else
Node[i].lchild = -1;
cin>>temp;
if(temp[0]>='0'&&temp[0]<='9'){
Node[i].rchild = temp[0] - '0';
hashtable[temp[0] - '0'] = 1;
}
else
Node[i].rchild = -1;
}
int root;
for(int i = 0;i < N;i++){ //寻找根节点
if(hashtable[i]==0){
root = i;
break;
}
}
layerorder(root);
printf("\n");
flag = 0;
inorder(root);
return 0;
}