天天看點

PAT甲級1102

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<iostream>
#include<queue>
using namespace std;
const int maxn = 10;
struct node
{
  int data;
  int lchild, rchild;
  node():data(-1),lchild(-1),rchild(-1){}
}nodes[maxn];
void levelOrder(int root)
{
  queue<int> Q;
  if (root!=-1)
  {
    Q.push(root);
  }
  bool flag = false;
  while (!Q.empty())
  {
    int f = Q.front();
    if (!flag)
    {
      cout << nodes[f].data;
      flag = true;
    }
    else
    {
      cout << " " << nodes[f].data;
    }
    Q.pop();
    if (nodes[f].rchild != -1) Q.push(nodes[f].rchild);
    if (nodes[f].lchild != -1) Q.push(nodes[f].lchild);
  }
}
bool flag = false;
void inOrder(int root)
{
  if (root == -1)
  {
    return;
  }
  inOrder(nodes[root].rchild);
  if (!flag)
  {
    cout << nodes[root].data;
    flag = true;
  }
  else
  {
    cout <<" "<<nodes[root].data;
  }
  inOrder(nodes[root].lchild);
}
int main()
{
  int N;
  scanf("%d", &N);
  char lchar, rchar;
  bool hashtable[maxn] = { false };
  for (int i = 0; i < N; i++)
  {
    cin >> lchar >> rchar;
    if (lchar != '-')
    {
      nodes[i].lchild = lchar - '0';
      hashtable[lchar - '0'] = true;
    }
    if (rchar != '-')
    {
      nodes[i].rchild = rchar - '0';
      hashtable[rchar - '0'] = true;
    }
    nodes[i].data = i;
  }
  int root;
  for (int i = 0; i < N; i++)
  {
    if (!hashtable[i])
    {
      root = i;
      break;
    }
  }
  levelOrder(root);
  cout << endl;
  inOrder(root);
  return 0;
}      
上一篇: PAT甲級1020
下一篇: PAT甲級1097

繼續閱讀