【PTA-A】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

这道题目没有很难,数据范围也在10以内,用一个结构体存储左右孩子和父节点,就可以实现,甚至连反转也不需要,只需要反向一下传统套路,也就是变成先右再左。

思路:

1.结构体存储孩子和父节点

2.输入左右孩子,节点1的左孩子为2,则数组a[1].lchild=2,a[2].parent=1

3.寻找并记录父节点

4.(该步骤在该题目可省略)翻转,交换每个节点的左右孩子

5.利用队列层序遍历,中序遍历

注意点:

1.注意空格,最后一位没有空格

2.学习层序和中序的遍历方式

#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int parent = 0,n;
int num = 0;
struct Node {
	int lchild = -1, rchild =-1, p = -1;
}no[15];
//层序遍历
void BFS() {
	queue<int> q;
	q.push(parent);
	while (!q.empty()) {
		int now = q.front();
		q.pop();
		cout << now; num++;
		if (num < n)cout << " ";
		if (no[now].rchild!=-1) {
			q.push(no[now].rchild);
		}
		if (no[now].lchild != -1) {
			q.push(no[now].lchild);
		}
	}
}
//中序遍历
void inorder(int temp) {
	if (temp == -1) {
		return;
	}
	inorder(no[temp].rchild);
	cout << temp; num++;
	if (num < n)cout << " ";
	inorder(no[temp].lchild);
}
int main() {
	char l,r;
	cin >> n;
	//存储左右孩子和父节点
	for (int i = 0; i < n; i++) {
		cin >> l >> r;
		if (l >= '0' && l <= '9') {
			no[i].lchild = l - '0';
			no[l-'0'].p = i;
		}
		if (r >= '0' && r <= '9') {
			no[i].rchild = r - '0';
			no[r - '0'].p = i;
		}
	}
	//寻找父节点
	int temp=0;
	for (int i = 0; i < n; i++) {
		if (no[temp].p!=-1) {
			parent = no[temp].p;
			temp = no[temp].p;
		}
		else {
			break;
		}
	}
	BFS();
	cout<<endl;
	num = 0;
	inorder(parent);
	return 0;
}

 

posted @ 2019-10-25 20:51  大帅本帅  阅读(7)  评论(0)    收藏  举报