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

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

题意:

要求反转二叉树,输出层次和中序遍历

记录知识点:后序遍历可以反转二叉树。

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
#include"bits/stdc++.h"
using namespace std;
struct Node{
	int l = -1;
	int r = -1;
};
const int maxn = 20;
Node nodes[maxn];
int getNum(const string& s){
	if(s[0] == '-')
		return -1;
	else 
		return stoi(s);
}
bool blank = false;
void layerOrder(int id){
	queue<int> q;
	q.push(id);
	while(!q.empty()){
		int t = q.front();
		q.pop();
		if(blank)
			printf(" ");
		else
			blank = true;
		printf("%d",t);
		if(nodes[t].l != -1) q.push(nodes[t].l);
		if(nodes[t].r != -1) q.push(nodes[t].r);
	}
}
void inOrder(int id){
	if(id == -1)
		return;
	inOrder(nodes[id].l);
	if(blank)
		printf(" ");
	else
		blank = true;
	printf("%d",id);
	inOrder(nodes[id].r);
}
void reverseTree(int id){
	if(id == -1)
		return;
	reverseTree(nodes[id].l);
	reverseTree(nodes[id].r);
	swap(nodes[id].l,nodes[id].r);	
}

int main(){
	//freopen("input.txt","r",stdin);
	int n; cin >> n;
	map<int,int> notRoot;
	for(int i=0;i<n;i++){
		string s1,s2;
		cin >> s1 >> s2;
		int t1 = getNum(s1);
		int t2 = getNum(s2);
		nodes[i].l = t1; nodes[i].r = t2;
		notRoot[t1] = 1; notRoot[t2] = 1;
	}
	int root;
	for(int i=0;i<n;i++){
		if(!notRoot[i]){
			root = i;
			break;
		}
	}
	reverseTree(root);
	layerOrder(root);
	printf("\n"); blank = false;
	inOrder(root);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值