PAT Advanced 1102 Invert a Binary Tree (25分)

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 (≤) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N1. Then N lines follow, each corresponds to a node from 0 to N1, 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

这题是依次给出节点的左孩子右孩子,进行找出翻转二叉树的层序遍历和中序遍历。

我们可以使用中序遍历进行构建树,之后进行使用sort根据level进行从小到大,根据index进行从大到小。即可获得翻转二叉树的层序遍历。

最后打印

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct node {
    int index, id, left = -1, right = -1, level;
}a[100];
int N;
vector<node> v;
bool cmp(node& n1, node& n2){
    return n1.level == n2.level ? n1.index > n2.index: n1.level < n2.level;
}
void dfs(int root, int index, int level){
    if(a[root].right != -1) dfs(a[root].right, index * 2 + 2, level + 1);
    v.push_back({index, root, 0, 0, level});
    if(a[root].left != -1) dfs(a[root].left, index * 2 + 1, level + 1);
}
int main(){
    cin >> N;
    string tmp_l, tmp_r;
    vector<bool> find_root(N);
    for(int i = 0; i < N; i++){
        cin >> tmp_l >> tmp_r;
        a[i].id = i;
        if(tmp_l != "-") {
            a[i].left = stoi(tmp_l);
            find_root[stoi(tmp_l)] = true;
        }
        if(tmp_r != "-") {
            a[i].right = stoi(tmp_r);
            find_root[stoi(tmp_r)] = true;
        }
    }
    int root_index;
    for(int i = 0; i < N; i++)
        if(!find_root[i]) root_index = i;
    dfs(root_index, 0, 0);
    vector<node> v2(v);
    sort(v2.begin(), v2.end(), cmp);
    for(int i = 0; i < N; i++)
        if(i != N-1) cout << v2[i].id << " ";
        else cout << v2[i].id <<endl;
    for(int i = 0; i < N; i++)
        if(i != N-1) cout << v[i].id << " ";
        else cout << v[i].id <<endl;
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/littlepage/p/12234525.html