A1102 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
思路:反转二叉树,输出层次/中序遍历,在遍历时调整遍历左右子树的顺序即可达到,无需调整树的结构!
注意事项:注意层序遍历入队时,入的是刚输出的now结点的孩子,而不是root的孩子——会死循环!
AC代码:
#include<cstdio>
#include<iostream>
#include<queue>
#include<string>
using namespace std;
struct node{
int lchild,rchild;
}Node[11];
bool isRoot[11] = {false};
void BFS(int root){
queue<int> q;
q.push(root);
int tag = 0;
while(!q.empty()){
int now = q.front();
q.pop();
if(tag == 0){
printf("%d",now);
tag = 1;
}
else printf(" %d",now);
if(Node[now].rchild != -1)
q.push(Node[now].rchild);
if(Node[now].lchild != -1)
q.push(Node[now].lchild);
}
printf("\n");
}
int cnt = 0;
void inTraversal(int root){
if(root != -1){
inTraversal(Node[root].rchild);
if(cnt == 0){
printf("%d",root);
cnt++;
}
else printf(" %d",root);
inTraversal(Node[root].lchild);
}
}
int main(){
int N;
scanf("%d",&N);
for(int i = 0; i < N; i++){
string left,right;
cin>>left>>right;
if(left != "-"){
Node[i].lchild = stoi(left);
isRoot[stoi(left)] = true;
}
else Node[i].lchild = -1;
if(right != "-"){
Node[i].rchild = stoi(right);
isRoot[stoi(right)] = true;
}
else Node[i].rchild = -1;
}
int root = 0 ;
while(isRoot[root]) root++;
BFS(root);
inTraversal(root);
return 0;
}