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
题意
给出一个二叉树,求它的反转二叉树(左右结点交换)的中序遍历和后序遍历。第i行(i=0,1……N-1)分别为原二叉树结点i的左右结点
思路
关于反转这个事情非常简单,我们只需要将输入的左结点作为建树的右结点,输入的右结点作为建树的左结点。因为这道题输入很小,我们可以使用数组来存储这棵二叉树。left[u]=v代表节点u的左子结点为v。类似的,我们使用left、right和parent这三个一维int型数组就可以表示一棵二叉树,这三个数组初始每个元素都是-1,代表不存在响应的连接。这里使用parent的原因是题目没有显式给出树的根结点。最优的方法是从任一有效结点递归查找它的父结点,直到找到根结点(parent[u]=-1,则u是根结点),但是由于题目输入很小,遍历所有结点的parent也不慢。最后层次遍历我们使用了队列,当然使用dfs也可以,中序遍历可以使用栈,当然我们使用了dfs。如果要练习自己的能力,可以将另外一种实现(使用dfs实现层次遍历、使用栈实现中序遍历)写出。
代码
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
#define MAX_N 10
int parent[1 << MAX_N], left[1 << MAX_N], right[1 << MAX_N];
int N;
// 解析结点
void parse(char c, int i, int sub[]){
if(c == '-'){
return;
}else{
int n = c - '0';
sub[i] = n;
parent[n] = i;
}
}
// 打印序列
void print(queue<int> &q){
printf("%d", q.front());
q.pop();
while (!q.empty()) {
printf(" %d", q.front());
q.pop();
}
}
// 层次遍历
void levelScan(int root){
queue<int> res, temp;
temp.push(root);
while (!temp.empty()) {
for(int i = 0, x , l = (int)temp.size();i < l; i++){
x = temp.front();
temp.pop();
res.push(x);
if(left[x] != -1){
temp.push(left[x]);
}
if(right[x] != -1){
temp.push(right[x]);
}
}
}
print(res);
}
// 中序遍历
queue<int> inOrder;
void inScan(int x){
if(x == -1) return;
inScan(left[x]);
inOrder.push(x);
inScan(right[x]);
}
int main() {
// 读取输入并建树, 反转相当于把左右结点交换建树即可
scanf("%d", &N);
char l, r;
fill(parent, parent + N, -1);
fill(left, left + N, -1);
fill(right, right + N, -1);
getchar();
for(int i = 0; i < N; i++){
scanf("%c %c", &l, &r);
parse(l, i, right);
parse(r, i, left);
if(i != N - 1) getchar();
}
// 遍历找出根结点
int root = 0;
for(int i = 0; i < N; i++){
if(parent[i] == -1){
root = i;
break;
}
}
// 输出结果
levelScan(root);
putchar('\n');
inScan(root);
print(inOrder);
return 0;
}