Skip to content

1102 Invert a Binary Tree

Statement

Metadata

  • 作者: CHEN, Yue
  • 单位: 浙江大学
  • 代码长度限制: 16 KB
  • 时间限制: 400 ms
  • 内存限制: 64 MB

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 (\le 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

Solution

#include <bits/stdc++.h>
using namespace std;
const int N = 110;
struct E {
    int son[2];
    E() {
        son[0] = son[1] = -1;
    }
} e[N];
int n, vis[N];
vector<int> vec;
void bfs(int S) {
    queue<int> que;
    que.push(S);
    while (!que.empty()) {
        int u = que.front();
        que.pop();
        vec.push_back(u);
        if (e[u].son[1] != -1) {
            que.push(e[u].son[1]);
        }
        if (e[u].son[0] != -1) {
            que.push(e[u].son[0]);
        }
    }
}

void dfs(int u) {
    if (u == -1)
        return;
    dfs(e[u].son[1]);
    vec.push_back(u);
    dfs(e[u].son[0]);
}

void print(vector<int> vec) {
    for (int i = 0; i < n; ++i) printf("%d%c", vec[i], " \n"[i == n - 1]);
}

int main() {
    while (scanf("%d", &n) != EOF) {
        memset(e, -1, sizeof e);
        memset(vis, 0, sizeof vis);
        for (int i = 0; i < n; ++i) {
            static char x[10], y[10];
            scanf("%s %s", x, y);
            if (x[0] != '-') {
                int c = x[0] - '0';
                e[i].son[0] = c;
                vis[c] = 1;
            }
            if (y[0] != '-') {
                int c = y[0] - '0';
                e[i].son[1] = c;
                vis[c] = 1;
            }
        }
        int rt = -1;
        for (int i = 0; i < n; ++i) {
            if (!vis[i])
                rt = i;
        }
        vec.clear();
        bfs(rt);
        print(vec);
        vec.clear();
        dfs(rt);
        print(vec);
    }
    return 0;
}

Last update: May 4, 2022
Back to top