1592. 反转二叉树
原题传送:AcWing 1592. 反转二叉树
以下是来自Max Howell @twitter
的内容:
谷歌:我们的百分之九十的工程师都使用你编写的软件,但是你连在白板上反转二叉树都做不到,还是滚吧。
现在,请你证明你会反转二叉树。
输入格式
第一行包含一个整数 N N N ,表示树的结点数量。
所有结点编号从 0 0 0 到 N − 1 N-1 N−1 。
接下来
N
N
N 行,每行对应一个
0
∼
N
−
1
0 \sim N-1
0∼N−1 的结点,给出该结点的左右子结点的编号,如果该结点的某个子结点不存在,则用−
表示。
输出格式
输出反转后二叉树的层序遍历序列和中序遍历序列,每个序列占一行。
相邻数字之间用空格隔开,末尾不得有多余空格。
数据范围
1 ≤ N ≤ 10 1 \le N \le 10 1≤N≤10
输入样例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
思路一:
反向输出中序遍历和层序遍历。
题解一:
#include<bits/stdc++.h>
using namespace std;
const int N = 15;
int n;
int l[N], r[N];
int q[N];
bool has_father[N];
void bfs(int root)
{
int hh = 0, tt = 0, height = 0;
q[0] = root;
while(hh <= tt)
{
int head = hh, tail = tt;
while(hh <= tail)
{
int t = q[hh++];
if(l[t] != -1) q[++tt] = l[t];
if(r[t] != -1) q[++tt] = r[t];
}
reverse(q + head, q + tail + 1);
}
cout << q[0];
for(int i = 1; i < n; i++)
cout << " " << q[i];
cout << endl;
}
void dfs(int u, int& k)
{
if(u == -1)
return;
dfs(r[u], k);
cout << u;
if(++k != n)
cout << " ";
dfs(l[u], k);
}
int main()
{
cin >> n;
memset(l, -1, sizeof l);
memset(r, -1, sizeof r);
for(int i = 0; i < n; i++)
{
char lc, rc;
cin >> lc >> rc;
if(lc != '-')
{
l[i] = lc - '0';
has_father[l[i]] = true;
}
if(rc != '-')
{
r[i] = rc - '0';
has_father[r[i]] = true;
}
}
int root = 0;
while(has_father[root])
root++;
bfs(root);
int k = 0;
dfs(root, k);
return 0;
}
思路二:
先将树反转,然后输出中序遍历和层序遍历。
题解二:
#include<bits/stdc++.h>
using namespace std;
const int N = 15;
int n;
int l[N], r[N];
int w[N], q[N];
bool has_father[N];
void dfs_reverse(int u)
{
if(u == -1)
return;
dfs_reverse(l[u]);
dfs_reverse(r[u]);
swap(l[u], r[u]);
}
void bfs(int root)
{
int hh = 0, tt = 0;
q[0] = root;
while(hh <= tt)
{
int t = q[hh++];
if(l[t] != -1)
q[++tt] = l[t];
if(r[t] != -1)
q[++tt] = r[t];
}
cout << q[0];
for(int i = 1; i < n; i++)
cout << " " << q[i];
cout << endl;
}
void dfs(int u, int& k)
{
if(u == -1)
return;
dfs(l[u], k);
cout << u;
if(++k != n)
cout << " ";
dfs(r[u], k);
}
int main()
{
cin >> n;
memset(l, -1, sizeof l);
memset(r, -1, sizeof r);
for(int i = 0; i < n; i++)
{
char lc, rc;
cin >> lc >> rc;
if(lc != '-')
{
l[i] = lc - '0';
has_father[l[i]] = true;
}
if(rc != '-')
{
r[i] = rc - '0';
has_father[r[i]] = true;
}
}
int root = 0;
while(has_father[root])
root++;
dfs_reverse(root);
bfs(root);
int k = 0;
dfs(root, k);
return 0;
}