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

原题链接1102 Invert a Binary Tree (25 分)

题目大意:

题目给定你一颗镜像翻转的二叉树(即左右子树翻转),让你进行层次遍历中序遍历

分析:

注意点:

  • 题目没有告诉你哪个是根结点,所以在读入的时候进行标记,对每行输入的点标记它们已有父结点,然后遍历一下就知道哪个点没有父结点了,没有父结点的就是根节点。
  • BFSDFS细心就可以了!

满分代码:

#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 10+10;

int l[MAXN], r[MAXN], q[MAXN];
int n, flag = 0;
bool has_father[MAXN];

void bfs(int root) {
	int st = 0, en = 0;
	q[0] = root;
	while(st <= en) {
		int t = q[st++];
		if(l[t] != -1)	q[++en] = l[t];
		if(r[t] != -1)	q[++en] = r[t];
	}
	cout << q[0];
	for(int i = 1; i < n; i++) {
		cout << " " << q[i];
	}
	cout << endl;
}

void dfs(int u) {
	if(u == -1)    return;
	dfs(l[u]);
	if(flag == 1) {
		cout << " ";
	}else {
		flag = 1;
	}
	cout << u;
	dfs(r[u]);	
}

int main() {
	cin >> n;
	memset(l, -1, sizeof l);
	memset(r, -1, sizeof r);
	for(int i = 0; i < n; i++) {
		string rr, ll;
		cin >> rr >> ll;
		if(rr[0] != '-')	r[i] = rr[0] - '0', has_father[r[i]] = true;
		if(ll[0] != '-')	l[i] = ll[0] - '0', has_father[l[i]] = true;
	}
	int root = -1;
	for(int i = 0; i < n; i++) {
		if(has_father[i] == false) {
			root = i;
			break;
		}
	}
	bfs(root);
	dfs(root);
	cout << endl;
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值