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 6Sample Output:
3 7 2 6 4 0 5 1 6 5 7 4 3 2 0 1
分析:二叉树转换
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <queue>
#include <vector>
#include <functional>
#define rep(i,j,k) for(int i=j;i<=k;++i)
const int Max=10;
int c[Max];
using namespace std;
struct node
{
int left;
int right;
};
queue<int> q;
int n;
node a[Max];
void invert(int r)
{
if (r!=-1){
swap(a[r].left,a[r].right);
invert(a[r].left);
invert(a[r].right);
}
}
void level(int r)
{
q.push(r);
while (!q.empty()){
r=q.front();
q.pop();
if (a[r].left!=-1) q.push(a[r].left);
if (a[r].right!=-1) q.push(a[r].right);
cout<<r;
if (!q.empty()) cout<<' ';
}
cout<<endl;
}
void inorder(int r)
{
if (a[r].left!=-1) inorder(a[r].left);
q.push(r);
if (a[r].right!=-1) inorder(a[r].right);
}
void in_print(int root)
{
inorder(root);
while (!q.empty()){
cout<<q.front();
q.pop();
if (!q.empty()) cout<<' ';
}
cout<<endl;
}
int main()
{
// freopen("test.txt","r",stdin);
cin>>n;
char x,y;
rep(i,0,n-1){
cin>>x>>y;
if (x=='-') a[i].left=-1;
else {
a[i].left=x-'0';
c[x-'0']=1;
}
if (y=='-') a[i].right=-1;
else {
a[i].right=y-'0';
c[y-'0']=1;
}
}
int root=0;
rep(i,0,n-1){
if (c[i]!=1) {
root=i;
break;
}
}
invert(root);
level(root);
in_print(root);
return 0;
}