原题链接:1102 Invert a Binary Tree (25分)
关键词:树的遍历、dfs、结构体排序
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
题目大意: 给出你树的结点的左右孩子情况,让你输出这个树倒置之后的层序遍历和中序遍历。
分析: invert倒置,也就是将二叉树的左右孩子全部互换,输出的时候只要在dfs中按照右根左的顺序存入数组即可。至于层序遍历,需要对结构体数组进行排列,因为倒置的关系,将level按照从小到大排序,当level相等时,按照index从大到小排列即可。
代码:
//pat 1102
#include <bits/stdc++.h>
using namespace std;
struct node{
int id, l, r, index, level; //id是题目给的结点顺序 index是在实际树中的结点顺序 level层数
}a[15];
int n;
vector<node> v1; //中序
void dfs(int root, int index, int level){ //二叉树反转,左右孩子交换 ,中序右根左
if(a[root].r != -1) dfs(a[root].r, index*2+2, level+1);
v1.push_back({root, 0, 0, index, level}); //在输出过程中l和r用不到
if(a[root].l != -1) dfs(a[root].l, index*2+1, level+1);
}
bool cmp(node a, node b){ //按照层数递增,层数相同时index递减
if(a.level != b.level) return a.level < b.level;
return a.index > b.index;
}
int main(){
cin >> n;
int havep[15] = {0}, root = 0; //havep 是否有父结点
for(int i = 0; i < n; i ++ ){
string s1, s2;
cin >> s1 >> s2;
if(s1 != "-"){
a[i].l = stoi(s1);
havep[stoi(s1)]= 1;
}
else a[i].l = -1;
if(s2 != "-"){
a[i].r = stoi(s2);
havep[stoi(s2)] = 1;
}
else a[i].r = -1;
}
while(havep[root] == 1) root++; //找到根
dfs(root, 0, 0);
vector<node> v2(v1); //v2 层序遍历
sort(v2.begin(), v2.end(), cmp);
//输出
for(int i = 0; i < n; i ++ ){
if(i != 0) cout << " ";
cout << v2[i].id;
}
cout << endl;
for(int i = 0; i < n; i ++ ){
if(i != 0) cout << " ";
cout << v1[i].id;
}
return 0;
}
注意:
vector<node> v2(v1); //用v1给v2初始化