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
对于这种输入,多半是建静态树,画下树的图,很容易发现规律。
#include<bits/stdc++.h>
using namespace std;
struct node{
int data,lchild,rchild;
}T[100];
int k=0;
void Inorder(int root){
if(root==11)return ;
Inorder(T[root].lchild);
if(k++)cout<<' ';
cout<<T[root].data;
Inorder(T[root].rchild);
}
void levelorder(int root){
queue<int>q;
q.push(root);
int i=0;
while(!q.empty()){
int root=q.front();
q.pop();
if(i++)cout<<' ';
cout<<root;
if(T[root].lchild!=11) q.push(T[root].lchild);
if(T[root].rchild!=11) q.push(T[root].rchild);
}
}
int G[15][15];
int main(){
int N;
cin>>N;
for(int i=0;i<N;i++){
char l,r;
getchar();
scanf("%c %c",&r,&l);
if(l!='-'){
T[i].lchild=l-'0';
G[i][l-'0']=1;
}
else T[i].lchild=11;
if(r!='-'){
T[i].rchild=r-'0';
G[i][r-'0']=1;
}
else T[i].rchild=11;
T[i].data=i;
}
int root;
for(int i=0;i<N;i++){
int is=1;
for(int j=0;j<N;j++)
if(G[j][i]!=0)is=0;
if(is)root=i;
}
levelorder(root);
cout<<endl;
Inorder(root);
return 0;
}