PAT A1102 Invert a Binary Tree (25point(s))

Scroll Down

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

题意

给出一棵二叉树,反转该二叉树,并输出层次遍历序列和中序遍历序列

解答

输入数据是n个结点的孩子编号,因此在未得到所有输入数据之前无法得知根结点。与树有关的题,一般使用链式存储结构,本题也是这样,因为结点数较少,所以可以使用数组存储所有结点。找根结点有以下两种方法:

  1. 没有在输入数据中出现的编号就是根结点的编号,如样例的根结点就为3。
  2. 任意选择一个编号,递归搜索,当它不是任意结点的孩子时,它就是根结点。
    第一种方法比较简单,也容易实现,不容易出错。
    找到根结点之后,就可以反转二叉树了,核心算法就是先交换两个子孩子,然后继续反转两个孩子结点,因为它们也是二叉树。注意孩子结点的编号不是2i也不是2i+1,因为结点序号是无序的,要根据结构体成员来获取孩子编号。
    反转二叉树后,就可以使用层次遍历和中序遍历代码输出结果了。
#include<iostream>
#include<queue>

using namespace std;

struct node {
	int lchild, rchild;
}nodes[15];
int count1 = 0;
int findRoot(int j, int n) {
	for (int i = 0; i < n; i++) {
		if (i == j) continue;
		if (nodes[i].lchild == j || nodes[i].rchild == j)
			return findRoot(i, n);
	}
	return j;
}

void levelOrder(int root)
{
	queue<int> q;
	q.push(root);
	while (!q.empty()) {
		int t = q.front();
		q.pop();
		if (nodes[t].lchild != -1)
			q.push(nodes[t].lchild);
		if (nodes[t].rchild != -1)
			q.push(nodes[t].rchild);
		printf("%d", t);
		if (q.empty())
			printf("\n");
		else
			printf(" ");
	}
}

void invertTree(int root) {
	if (root!= -1) {
		swap(nodes[root].lchild, nodes[root].rchild);
		invertTree(nodes[root].lchild);
		invertTree(nodes[root].rchild);
	}
}

void inOrder(int root, int n) {
	if (root!= -1) {
		inOrder(nodes[root].lchild, n);
		printf("%d", root);
		count1++;
		if (n > count1) printf(" ");
		inOrder(nodes[root].rchild, n);
	}
}

int main()
{
	int n;
	char a[4], b[4];
	cin >> n;
	for (int i = 0; i < n; i++){
		scanf("%s %s", a, b);
		if (a[0] == '-') nodes[i].lchild = -1;
		else nodes[i].lchild = atoi(a);
		if (b[0] == '-') nodes[i].rchild = -1;
		else nodes[i].rchild = atoi(b);
	}
	int root = findRoot(0, n);
	invertTree(root);
	levelOrder(root);
	inOrder(root, n);
	return 0;
}