【PAT A1102】Invert a Binary Tree

在这里插入图片描述

#include <cstdio>
#include <queue>
#include <iostream>
using namespace std;

struct Node
{
	int lchild = -1, rchild = -1;
}Nodes[11];

bool isNotRoot[11];
int N;

int invert(int root){
	if(root == -1)
		return -1;
	int tmp = Nodes[root].rchild;
	Nodes[root].rchild = invert(Nodes[root].lchild);
	Nodes[root].lchild = invert(tmp);
	return root;
}

void levelTravel(int root){
	queue<int> q;
	q.push(root);
	int cnt = 0;
	while(!q.empty()){
		cnt++;
		if(cnt != N)
			printf("%d ", q.front());
		else
			printf("%d\n", q.front());
		int left = Nodes[q.front()].lchild, right = Nodes[q.front()].rchild;
		if(left >= 0)
			q.push(left);
		if(right >= 0)
			q.push(right);
		q.pop();
	}
}

void inTravel(int root, int &cnt){
	if(root == -1)
		return;
	inTravel(Nodes[root].lchild, cnt);
	cnt++;
	if(cnt == N)
		printf("%d\n", root);
	else
		printf("%d ", root);
	inTravel(Nodes[root].rchild, cnt);
}

int main(){
	scanf("%d", &N);
	getchar();
	for(int i = 0; i < N; i++)
		isNotRoot[i] = false;
	for(int i = 0; i < N; i++){
		string s;
		getline(cin, s);
		if(s[0] != '-'){
			isNotRoot[s[0] - '0'] = true;
			Nodes[i].lchild = s[0] - '0';
		}
		if(s[2] != '-'){
			isNotRoot[s[2] - '0'] = true;
			Nodes[i].rchild = s[2] - '0';
		}
	}
	int root;
	for(int i = 0; i < N; i++)
		if(!isNotRoot[i]){
			root = i;
			break;
		}
	invert(root);

	levelTravel(root);

	int cnt = 0;
	inTravel(root, cnt);

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值