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
解题思路:
本题涉及树的广度优先遍历(bfs,层序遍历)和深度优先遍历(中序遍历),此处题面提及反转二叉树,这里只需在输入环节将输入的数据反转(第一个数给右子树,第二个数给左子树)。
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node
{
int r,l;
};
vector<node>v;
void bfs(int root){
queue<int>q;
q.push(root);
bool first1=true;
while(!q.empty()){
int u=q.front();
if(first1){
cout<<u;
first1=false;
}else cout<<" "<<u;
q.pop();
if(v[u].l!=-1) q.push(v[u].l);
if(v[u].r!=-1) q.push(v[u].r);
}
cout<<endl;
}
bool isfirst2=true;
void in_travel(int u){
if(v[u].l!=-1) in_travel(v[u].l);
if(isfirst2) {
cout<<u;
isfirst2=false;
}else{
cout<<" "<<u;
}
if(v[u].r!=-1) in_travel(v[u].r);
}
int main(){
int n;
cin>>n;
v.resize(n);
vector<bool> exist(n,false);
for(int i=0;i<n;i++){
char x,y;
cin>>x>>y;
if(x=='-')v[i].r=-1;
else {
v[i].r=x-'0';
exist[v[i].r]=true;
}
if(y=='-') v[i].l=-1;
else{
v[i].l=y-'0';
exist[v[i].l]=true;
}
}
int root=0;
while(root<n && exist[root]==true) root++;
bfs(root);
in_travel(root);
cout<<endl;
return 0;
}