[PAT A1102]Invert a Binary Tree

[PAT A1102]Invert a Binary Tree

题目描述

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!

输入格式

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.

输出格式

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.

输入样例

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出样例

3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

解析

1.题目大意:首先输入一个N,表示一棵树的结点的个数,并且默认编号为0~N-1,然后输入N行数据,第i行代表的是编号为i-1的结点,并且依次输出它的左儿子和它的右儿子编号。然后我们需要将其翻转,即对于所有结点而言,将其左右儿子交换,然后输出新树的层序遍历序列和中序遍历序列。

2.我是使用了数组来存储这样的一棵二叉树,因为编号是从0~N-1是连续的,故使用数组虽然跟一般的树结构不同(用到指针),但是更好处理一些。

3.

#include<iostream>
#include<queue>
using namespace std;
const int maxn = 10; //结点个数不超过10
struct node {
	int parent = -1;      //定义该结点的父节点编号
	int lchild = -1, rchild = -1; //该结点的左右儿子编号
};
void level_traverse(int root); //层序遍历函数
void in_traverse(int root);  //中序遍历函数
node tree[maxn];
int n;
int main()
{
	int root = -1;
	cin >> n;
	getchar(); //去掉结尾的换行符
	for (int i = 0; i < n; i++) {
		char left, right;
		scanf("%c %c",&left, &right);
		getchar();  //去掉结尾的换行符
		if (left != '-') {       //如果左儿子不为空
			tree[i].rchild = left - '0';  //这里定义“交换”操作,交换左右儿子
			tree[left - '0'].parent = i;  //并且对于儿子结点的父亲结点编号是i
		}
		if (right != '-') {
			tree[i].lchild = right - '0';	//同理
			tree[right - '0'].parent = i;
		}
	}
	for (int i = 0; i < n; i++) {
		if (tree[i].parent == -1) { //这么多结点里面,没有父亲结点的结点就是根结点
			root = i;
			break;
		}
	}
	level_traverse(root);
	printf("\n");
	in_traverse(root);
	return 0;
}
void level_traverse(int root) {
	queue<int> que;
	que.push(root);
	while (!que.empty()) {
		int temp = que.front();
		printf("%d", temp);
		if (tree[temp].lchild != -1) que.push(tree[temp].lchild);
		if (tree[temp].rchild != -1) que.push(tree[temp].rchild);
		que.pop();
		if (!que.empty()) printf(" ");
	}
}
void in_traverse(int root) {
	if (root == -1) return;
	in_traverse(tree[root].lchild);
	printf("%d", root);
	n--;
	if (n != 0) printf(" ");
	in_traverse(tree[root].rchild);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值