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 (<=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<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 15;
struct node{
    int lchild,rchild;
}Node[maxn];
bool isRoot[maxn] = {false};
int n,num = 0; 

void print(int i){
    printf("%d",i);
    num++;
    if(num < n)printf(" ");
    else printf("\n");
}
void inOrder(int root){
    if(root == -1) return;
    inOrder(Node[root].lchild);
    print(root);
    inOrder(Node[root].rchild);
} 
void BFS(int root){
    queue<int> q;
    q.push(root);
    while(!q.empty()){
        int now = q.front();
        q.pop();
        print(now);
        if(Node[now].lchild != -1) q.push(Node[now].lchild);
        if(Node[now].rchild != -1) q.push(Node[now].rchild);
    }
}
void postOrder(int root){
    if(root == -1) return;
    postOrder(Node[root].lchild);
    postOrder(Node[root].rchild);
    swap(Node[root].lchild,Node[root].rchild);
}
int findRoot(){
    for(int i = 0; i < n; i++){
        if(isRoot[i] == false) return i;
    }
}
int strToint(char c){
    if(c == '-') return -1;
    else{
        isRoot[c - '0'] = true;
        return c - '0';
    }
}
 int main(){
  char lchild,rchild;
  scanf("%d",&n);
  for(int i = 0; i < n; i++){
      scanf("%*c%c %c",&lchild,&rchild);
      Node[i].lchild = strToint(lchild);
      Node[i].rchild = strToint(rchild);
  }
  int root = findRoot();
  postOrder(root);
  BFS(root);
  num = 0;//全局定义初始化的值已经在层序遍历的时候加过了 
  inOrder(root);
  return 0;
}

 

posted @ 2018-03-14 16:31  王清河  阅读(123)  评论(0编辑  收藏  举报