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.
invert 英[ɪnˈvɜːt]
美[ɪnˈvɜːrt]
v. (使) 倒转,颠倒,倒置;
indices 英[ˈɪndɪsiːz]
美[ˈɪndɪsiːz]
[词典] index 的复数形式之一;
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.我掌握了静态的建树,静态的level inoder 访问
2.根节点,小技巧,有一个从没做过子节点的就是根,有bool标记
3.很简单的scanf能读取空格,在读取字符的时候。。。虽然是基础点但还是忘记了
4.Invert 没读懂一开始,反转二叉树只要建树的时候取反就可以了
#include<iostream>
#include<cstdio>
#include<queue>
const int maxn=50;
using namespace std;
struct node{
int lchild,rchild;
}Node[maxn];
bool notroot[maxn]={false};
int n;
void bfs(int root){
int num=-1;
queue<int> q;
q.push(root);
while(!q.empty()){
int top = q.front();
q.pop();
++num;
if(num < n-1) cout<<top<<' ';
else cout<<top;
if(Node[top].lchild != -1) q.push(Node[top].lchild);
if(Node[top].rchild != -1) q.push(Node[top].rchild);
}
}
int num1=-1;
void inorder(int root){
if(root == -1) return ;
inorder(Node[root].lchild);
num1++;
if(num1 < n-1) cout<<root <<' ';
else cout<<root;
inorder(Node[root].rchild);
}
int main(){
scanf("%d",&n);
getchar();
for(int i=0;i<n;i++){
char a,b;
scanf("%c %c",&a,&b);
getchar();
if(a != '-'){
Node[i].rchild = a-'0';
notroot[a-'0'] = true;
}
else{
Node[i].rchild=-1;
}
if(b != '-'){
Node[i].lchild = b-'0';
notroot[b -'0'] = true;
}
else{
Node[i].lchild=-1;
}
}
int root;
for(int i=0;i<n;i++){
if(!notroot[i]) {
root = i;
break;
}
}
bfs(root);
cout<<endl;
inorder(root);
return 0;
}