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
解题思路:
这道题应该说还是挺简单的,就是给你一棵二叉树,让你输出其镜像二叉树(左右子树翻转)的层序遍历和中序遍历。
在输入数据的时候需要注意,因为有可能接收到表示空树的 - 号,所以需要用char类型接收,并且在接收到换行符和空格的时候需要忽略。
由于题目直接用标号表示结点,所以可以用数组记录这棵二叉树,数组元素记录该结点的父结点,在遍历之前需要找到二叉树的根结点,我们使用一个数组isRoot记录在输入数据过程中是否遇到这个结点,如果遇到了那么就说明这个结点不是二叉树的根节点。
最后进行层序遍历和中序遍历就行啦。
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
struct Node{
int lchild, rchild;
}node[MAXSIZE];
//int isExist[MAXSIZE] = {0};
int isRoot[MAXSIZE];
int n;
void init(){
for(int i=0; i<MAXSIZE; i++){
node[i].lchild=-1;
node[i].rchild=-1;
isRoot[i] = 1;
}
}
int findRoot(){
int idx;
for(idx=0; idx<MAXSIZE; idx++){
if((isRoot[idx]==1 && idx<n)){
break;
}
}
return idx;
}
void levelorder(int root){
int queue[MAXSIZE];
int st=0;
int ed=0;
queue[ed++] = root;
int cnt = 0;
while(st != ed){
if(cnt == 0){
cnt++;
} else {
printf(" ");
}
int q = queue[st++];
printf("%d", q);
if(node[q].rchild!=-1){
queue[ed++] = node[q].rchild;
}
if(node[q].lchild!=-1){
queue[ed++] = node[q].lchild;
}
}
printf("\n");
}
int num = 1;
void inorder(int root){
if(root==-1) return;
inorder(node[root].rchild);
if(num == 1){
num++;
} else {
printf(" ");
}
printf("%d", root);
inorder(node[root].lchild);
}
int main(){
init();
scanf("%d", &n);
getchar();
char a, b;
for(int i=0; i<n; i++){
scanf("%c", &a);
getchar(); //空格
scanf("%c", &b);
getchar(); //换行
if(a != '-'){
int tmp = a-'0';
//isExist[tmp] = 1;
node[i].lchild = tmp;
isRoot[tmp] = 0;
} else {
node[i].lchild = -1;
}
if(b != '-'){
int tmp = b-'0';
//isExist[tmp] = 1;
node[i].rchild = tmp;
isRoot[tmp] = 0;
} else {
node[i].rchild = -1;
}
}
int root = findRoot();
levelorder(root);
inorder(root);
return 0;
}