天天看点

PAT (Advanced Level) Practise 1102 Invert a Binary Tree (25)

1102. Invert a Binary Tree (25)

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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

输出反转二叉树的层次和先序遍历。

#include<cstdio>
#include<vector>
#include<queue>
#include<string>
#include<map>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int INF = 0x7FFFFFFF;
const int maxn = 1e5 + 10;
int n, ch[maxn][2], flag[maxn];
char s[maxn];

int get()
{
  scanf("%s", s);
  return s[0] == '-' ? -1 : s[0] - '0';
}

void dfs(int x, int &flag)
{
  if (x == -1) return;
  dfs(ch[x][1], flag);
  if (flag) printf(" "); else flag = 1;
  printf("%d", x);
  dfs(ch[x][0], flag);
}

int main()
{
  scanf("%d", &n);
  for (int i = 0; i < n; i++)
  {
    ch[i][0] = get(); if (ch[i][0] != -1) flag[ch[i][0]] = 1;
    ch[i][1] = get(); if (ch[i][1] != -1) flag[ch[i][1]] = 1;
  }
  for (int i = 0; i < n; i++)
  {
    if (flag[i]) continue;
    queue<int> p; p.push(i);
    while (!p.empty())
    {
      int q = p.front();  p.pop();
      printf("%s%d", i == q ? "" : " ", q);
      if (ch[q][1] != -1) p.push(ch[q][1]);
      if (ch[q][0] != -1) p.push(ch[q][0]);
    }
    printf("\n");
    int x = 0; dfs(i, x);
    printf("\n");
  }
  return 0;
}