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 -
- -
- -
2 7
- -
- -
- -
4 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
#include <iostream>
#include <vector>
#include<algorithm>
#include <cmath>
#include<map>
#include<cstring>
#include<queue>
#include<string>
#include<set>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn=110,inf=100000000;
struct node{
int data,rchild,lchild;
}s[maxn];
int n,a[maxn],b[maxn],root;bool not_root[maxn]={0};vector<int>v;
int t=0;
void in(int root){
if(root==-1) return;
in(s[root].lchild);
if(t!=0) cout<<" ";
cout<<root;t++;
in(s[root].rchild);
}
void level(int root){
queue<int>q;
q.push(root);int i=0;
while(!q.empty()){
int now=q.front();
if(s[now].lchild!=-1) q.push(s[now].lchild);
if(s[now].rchild!=-1) q.push(s[now].rchild);
if(i!=0) cout<<" ";
cout<<now;i++;
q.pop();
}
}
int main(){
cin>>n;string v1,v2;
for(int i=0;i<n;i++){ //正经方法是后序遍历有子结点,swap其左右孩子;
cin>>v1>>v2;
if(v1=="-") s[i].rchild=-1;
else{
s[i].rchild=stoi(v1);not_root[stoi(v1)]=1;
}
if(v2=="-") s[i].lchild=-1;
else {
s[i].lchild=stoi(v2);not_root[stoi(v2)]=1;
}
}
for(int i=0;i<n;i++) if(!not_root[i]){
root=i;break;
}
level(root);cout<<endl;
in(root);
}

浙公网安备 33010602011771号