PAT甲级1102 Invert a Binary Tree (25 分)

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 N1. Then N lines follow, each corresponds to a node from 0 to N1, 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个结点的二叉树,每一行都是结点i的左右孩子编号,I 从 0 ~ n – 1。要求反转整棵树然后输出他的层序与中序。

 

 

思路:

         首先需要建树,而且明确指出了结点是整数编号的用静态二叉树。其次反转二叉树,只要在存储的时候存储顺序反过来即可。

         对于中序遍历的时候,记录相应的层次,然后sort一遍就可以知道层序了。由于在排序的时候,层数小的排前面,同样层数的,编号小的排前面。也即在中序遍历的时候也要重新编号。

         最后如何找到根节点?在存储的时候,进行标志,找到没有父结点的即可。当然也可以用常规的并查集方法。

参考代码:

 

 

#include<string>
#include<vector>
#include<iostream>
#include<cctype>
#include<algorithm>
using namespace std;
struct node{
	int id, l, r, level, idx;
};
vector<node> t, ans;
vector<bool> fn;
int n, root;
void inorder(int v, int level, int idx){
	if(v == -1)	return;
	inorder(t[v].l, level + 1, idx * 2 + 1);
	ans.push_back({v,0,0,level, idx});
	inorder(t[v].r, level + 1, idx * 2 + 2);
}
bool cmp(node a, node b){
	if(a.level != b.level)	return a.level < b.level;
	else	return  a.idx < b.idx;
}
int main(){
	scanf("%d", &n);
	t.resize(n), fn.resize(n);
	for(int i = 0; i < n; ++i){
		string s1, s2;
		cin >> s1 >> s2;
		if(isdigit(s1[0])){
			fn[stoi(s1)] = true;
			t[i].r = stoi(s1);
		}else	t[i].r = -1;
		if(isdigit(s2[0])){
			fn[stoi(s2)] = true;
			t[i].l = stoi(s2);
		}else t[i].l = -1;
	}
	while(fn[root]) root++;
	inorder(root, 0, 0);
	vector<node> temp(ans);
	sort(ans.begin(), ans.end(), cmp);
	for(int i = 0; i < n; ++i)
		printf("%d%c", ans[i].id, i != n - 1?' ': '\n');
	for(int i = 0; i < n; ++i)
		printf("%d%c", temp[i].id, i != n - 1? ' ': '\n');
	return 0;
}

代码参考:https://blog.csdn.net/liuchuo/article/details/52175736

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值