原题链接:1102 Invert a Binary Tree (25 分)
题目大意:
题目给定你一颗镜像翻转的二叉树(即左右子树翻转),让你进行层次遍历
和中序遍历
。
分析:
注意点:
- 题目没有告诉你哪个是根结点,所以在读入的时候进行标记,对每行输入的点标记它们已有父结点,然后遍历一下就知道哪个点没有父结点了,没有父结点的就是根节点。
BFS
和DFS
细心就可以了!
满分代码:
#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 10+10;
int l[MAXN], r[MAXN], q[MAXN];
int n, flag = 0;
bool has_father[MAXN];
void bfs(int root) {
int st = 0, en = 0;
q[0] = root;
while(st <= en) {
int t = q[st++];
if(l[t] != -1) q[++en] = l[t];
if(r[t] != -1) q[++en] = r[t];
}
cout << q[0];
for(int i = 1; i < n; i++) {
cout << " " << q[i];
}
cout << endl;
}
void dfs(int u) {
if(u == -1) return;
dfs(l[u]);
if(flag == 1) {
cout << " ";
}else {
flag = 1;
}
cout << u;
dfs(r[u]);
}
int main() {
cin >> n;
memset(l, -1, sizeof l);
memset(r, -1, sizeof r);
for(int i = 0; i < n; i++) {
string rr, ll;
cin >> rr >> ll;
if(rr[0] != '-') r[i] = rr[0] - '0', has_father[r[i]] = true;
if(ll[0] != '-') l[i] = ll[0] - '0', has_father[l[i]] = true;
}
int root = -1;
for(int i = 0; i < n; i++) {
if(has_father[i] == false) {
root = i;
break;
}
}
bfs(root);
dfs(root);
cout << endl;
return 0;
}