PAT 1102 Invert a Binary Tree

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

分析
用vector Left和right来记录每个节点的左孩子节点和右孩子节点,利用根节点不是任何节点的子节点来找到根节点root,在从根节点开始将节点依次插入树中,最后就是基本的层序遍历和中序遍历的实现了。

#include<iostream>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
vector<int> Left;
vector<int> Right;
int flag=1;
class node{
  public:
    int value;
    node* left=NULL;
    node* right=NULL;
    node(int val):value(val), left(NULL), right(NULL){
    }
};
void CreateTree(node* root){
  if(Left[root->value]!=-1){
    root->left=new node(Left[root->value]);
    CreateTree(root->left);
  }
  if(Right[root->value]!=-1){
    root->right=new node(Right[root->value]);
    CreateTree(root->right);
  }
}
void inorder(node* root){
  if(root->left)
    inorder(root->left);
  flag++==1?cout<<root->value:cout<<" "<<root->value;
  if(root->right)
    inorder(root->right);
}
int main(){
  int N;
  cin>>N;
  vector<int> record(N,0);
  Left.resize(N);
  Right.resize(N);
  for(int i=0; i<N; i++){
    char l, r;
    cin>>l>>r;
    if(isdigit(l)){
      Right[i]=l-'0';
      record[Right[i]]=1;
    }
    else
      Right[i]=-1;
    if(isdigit(r)){
      Left[i]=r-'0';
      record[Left[i]]=1;
    }
    else
      Left[i]=-1;
  }
  int i;
  for(i=0; i<N; i++)
    if(record[i]==0)
      break;
  node* root=new node(i);
  CreateTree(root);
  queue<node*> q;
  q.push(root);
  while(q.size()!=0){
    node* t=q.front();
    q.pop();
    flag++==1?cout<<t->value:cout<<" "<<t->value;
    if(t->left)
      q.push(t->left);
    if(t->right)
      q.push(t->right);
  }
  cout<<endl;
  flag=1;
  inorder(root);
  return 0;
}
posted @ 2018-08-19 17:20  A-Little-Nut  阅读(130)  评论(0编辑  收藏  举报