1102 Invert a Binary Tree (25 point(s))
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
题意:给定一棵二叉树,给出其反转树的层次遍历、中序遍历。
考察点:树的静态存储、寻找树的根、树的反转、树的遍历
思路:
1. 静态建立二叉树,同时标记儿子节点。完成后根据标记结果(有且仅有根节点没有被标记)找出根;
2. 由于要的是反转二叉树,存储时左子树、右子树反着存储即可;
3. 层次遍历(BFS);
4. 中序遍历(递归)。
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
struct Node{
int left=-1;int right=-1;
};
Node node[17];
bool visit[17]={false};
int string2int(string s){
int ans = 0;
for(int i=0;i<s.length();i++){
ans = ans*10+s[i]-'0';
}
return ans;
}
void levelOrder(int root,vector<int> &v){
queue<int> q;
q.push(root);
while(!q.empty()){
int top = q.front();
q.pop();
v.push_back(top);
if(node[top].left!=-1) q.push(node[top].left);
if(node[top].right!=-1) q.push(node[top].right);
}
}
void output(vector<int> &v){
for(int i=0;i<v.size();i++){
if(i==0) cout<<v[i];
else cout<<" "<<v[i];
}
cout<<endl;
v.clear();
}
void inOrder(int root,vector<int> &s){
if(node[root].left!=-1) inOrder(node[root].left,s);
s.push_back(root);
if(node[root].right!=-1) inOrder(node[root].right,s);
}
int main(void){
int N;cin>>N;
string a,b;
for(int i=0;i<N;i++){
cin>>a>>b;
if(a!="-"){//反着存储
node[i].right = string2int(a);
visit[node[i].right] = true;
}
if(b!="-"){
node[i].left = string2int(b);
visit[node[i].left] = true;
}
}
int root = find(visit,visit+N,false)-visit;
vector<int> s;
levelOrder(root,s);
output(s);
inOrder(root,s);
output(s);
return 0;
}