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
结尾无空行
百分之九十的谷歌程序员都会使用开发软件,但是不能反转一个二叉树!
本题,不需要建树(我一开始想的建立树,但是没实现),后来发现,其实用二维数组是一样的,因为题目中已经给出了左子树右子树了,所以二维数组更直观,开辟一个二维数组,第一个数表示左子树,第二个数表示右子树;
当层序遍历的时候,先让右子树入队,左子树收入队即可实现反转二叉树的层次遍历
当中序遍历的时候,正常的中序遍历是左根右,那么反转二叉树只需要变成右根左即可完成。
总结,对树的运用和题目的理解程度,是简单题
#include<iostream>
#include<bits/stdc++.h>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<deque>
#include<unordered_set>
#include<unordered_map>
#include<cctype>
#include<algorithm>
#include<stack>
using namespace std;
const int N = 11;
vector<int> level;
vector<int> in;
vector<int> tree[N];
void levelorder(int x) {
queue<int> qu;
qu.push(x);
while (!qu.empty()) {
int node = qu.front();
level.push_back(node);
qu.pop();
if (tree[node][1] != -1) {
qu.push(tree[node][1]);
}
if (tree[node][0] != -1) {
qu.push(tree[node][0]);
}
}
}
void inorder(int x) {
if (x != -1) {
inorder(tree[x][1]);
in.push_back(x);
inorder(tree[x][0]);
}
}
int main() {
int n;
cin >> n;
int isroot[n] = {0};
for (int i = 0; i < n; i++) {
string s1, s2;
cin >> s1 >> s2;
if (s1 == "-") {
tree[i].push_back(-1);
} else {
tree[i].push_back(stoi(s1));
isroot[stoi(s1)] = 1;
}
if (s2 == "-") {
tree[i].push_back(-1);
} else {
tree[i].push_back(stoi(s2));
isroot[stoi(s2)] = 1;
}
}
int root;
for (int i = 0; i < n; i++) {
if (!isroot[i]) {
levelorder(i);
inorder(i);
break;
}
}
for (int i = 0; i < level.size(); i++) {
if (!i) {
cout << level[i];
} else {
cout << " " << level[i];
}
}
cout << endl;
for (int i = 0; i < in.size(); i++) {
if (!i) {
cout << in[i];
} else {
cout << " " << in[i];
}
}
return 0;
}