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

解题思路:

这道题应该说还是挺简单的,就是给你一棵二叉树,让你输出其镜像二叉树(左右子树翻转)的层序遍历和中序遍历。

在输入数据的时候需要注意,因为有可能接收到表示空树的 - 号,所以需要用char类型接收,并且在接收到换行符和空格的时候需要忽略。

由于题目直接用标号表示结点,所以可以用数组记录这棵二叉树,数组元素记录该结点的父结点,在遍历之前需要找到二叉树的根结点,我们使用一个数组isRoot记录在输入数据过程中是否遇到这个结点,如果遇到了那么就说明这个结点不是二叉树的根节点。

最后进行层序遍历和中序遍历就行啦。 

#include 
#include  
#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

 

你可能感兴趣的:(OJ题)