题目地址:
https://www.acwing.com/problem/content/description/1594/
以下是来自Max Howell@twitter的内容:
谷歌:我们的百分之九十的工程师都使用你编写的软件,但是你连在白板上反转二叉树都做不到,还是滚吧。
现在,请你证明你会反转二叉树。
输入格式:
第一行包含一个整数
N
N
N,表示树的结点数量。所有结点编号从
0
0
0到
N
−
1
N−1
N−1。接下来
N
N
N行,每行对应一个
0
∼
N
−
1
0∼N−1
0∼N−1的结点,给出该结点的左右子结点的编号,如果该结点的某个子结点不存在,则用−
表示。
输出格式:
输出反转后二叉树的层序遍历序列和中序遍历序列,每个序列占一行。相邻数字之间用空格隔开,末尾不得有多余空格。
数据范围:
1
≤
N
≤
10
1≤N≤10
1≤N≤10
思路是递归,先建树,然后做翻转,接着做BFS和中序遍历的DFS。代码如下:
#include <iostream>
#include <queue>
using namespace std;
const int N = 15;
int n;
int l[N], r[N];
bool st[N];
string res;
void flip(int cur) {
if (cur == -1) return;
int tmp = l[cur];
l[cur] = r[cur];
r[cur] = tmp;
flip(l[cur]);
flip(r[cur]);
}
void bfs(int root) {
if (root == -1) return;
queue<int> q;
q.push(root);
while (q.size()) {
int t = q.front(); q.pop();
res += to_string(t) + " ";
if (l[t] != -1) q.push(l[t]);
if (r[t] != -1) q.push(r[t]);
}
}
void dfs(int root) {
if (root == -1) return;
dfs(l[root]);
res += to_string(root) + " ";
dfs(r[root]);
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
char left, right;
cin >> left >> right;
if (left != '-') {
l[i] = left - '0';
st[l[i]] = true;
} else l[i] = -1;
if (right != '-') {
r[i] = right - '0';
st[r[i]] = true;
} else r[i] = -1;
}
int root = -1;
for (int i = 0; i < n; i++)
if (!st[i]) root = i;
flip(root);
bfs(root);
res.pop_back();
cout << res << endl;
res = "";
dfs(root);
res.pop_back();
cout << res << endl;
return 0;
}
时空复杂度 O ( N ) O(N) O(N)。