【题解】【AcWing】1592. 反转二叉树

本文介绍了一道编程题目,要求反转二叉树并输出反转后的层序遍历和中序遍历序列。提供了两种解题思路,一种是直接反向输出中序遍历和层序遍历,另一种是先反转二叉树再输出遍历序列。代码实现分别采用BFS和DFS方法完成树的反转和遍历。
摘要由CSDN通过智能技术生成

1592. 反转二叉树

原题传送:AcWing 1592. 反转二叉树

以下是来自Max Howell @twitter的内容:

谷歌:我们的百分之九十的工程师都使用你编写的软件,但是你连在白板上反转二叉树都做不到,还是滚吧。

现在,请你证明你会反转二叉树。

输入格式

第一行包含一个整数 N N N ,表示树的结点数量。

所有结点编号从 0 0 0 N − 1 N-1 N1

接下来 N N N 行,每行对应一个 0 ∼ N − 1 0 \sim N-1 0N1 的结点,给出该结点的左右子结点的编号,如果该结点的某个子结点不存在,则用表示。

输出格式

输出反转后二叉树的层序遍历序列和中序遍历序列,每个序列占一行。

相邻数字之间用空格隔开,末尾不得有多余空格。

数据范围

1 ≤ N ≤ 10 1 \le N \le 10 1N10

输入样例:
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;

const int N = 15;

int n;
int l[N], r[N];
int q[N];
bool has_father[N];

void bfs(int root)
{
	int hh = 0, tt = 0, height = 0;
	q[0] = root;
	
	while(hh <= tt)
	{
		int head = hh, tail = tt;
		while(hh <= tail)
		{
			int t = q[hh++];
			if(l[t] != -1) q[++tt] = l[t];
			if(r[t] != -1) q[++tt] = r[t];
		}
		reverse(q + head, q + tail + 1);
	}
	
	cout << q[0];
	for(int i = 1; i < n; i++)
		cout << " " << q[i];
	cout << endl;
}

void dfs(int u, int& k)
{
	if(u == -1)
		return;
		
	dfs(r[u], k);
	
	cout << u;
	if(++k != n)
		cout << " ";
	
	dfs(l[u], k);
}

int main()
{	
	cin >> n;

	memset(l, -1, sizeof l);
	memset(r, -1, sizeof r);
	for(int i = 0; i < n; i++)
	{
		char lc, rc;
		cin >> lc >> rc;
		if(lc != '-')
		{
			l[i] = lc - '0';
			has_father[l[i]] = true; 
		}
		if(rc != '-')
		{
			r[i] = rc - '0';
			has_father[r[i]] = true; 
		}
	}
	
	int root = 0;
	while(has_father[root])
		root++;
	bfs(root);
	int k = 0;
	dfs(root, k);
	
	return 0;
}
思路二:

先将树反转,然后输出中序遍历和层序遍历。

题解二:
#include<bits/stdc++.h>

using namespace std;

const int N = 15;

int n;
int l[N], r[N];
int w[N], q[N];
bool has_father[N];

void dfs_reverse(int u)
{
	if(u == -1)
		return;
	
	dfs_reverse(l[u]);
	dfs_reverse(r[u]);
	swap(l[u], r[u]);
}

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

void dfs(int u, int& k)
{
	if(u == -1)
		return;
		
	dfs(l[u], k);
	
	cout << u;
	if(++k != n)
		cout << " ";
	
	dfs(r[u], k);
}

int main()
{	
	cin >> n;

	memset(l, -1, sizeof l);
	memset(r, -1, sizeof r);
	for(int i = 0; i < n; i++)
	{
		char lc, rc;
		cin >> lc >> rc;
		if(lc != '-')
		{
			l[i] = lc - '0';
			has_father[l[i]] = true; 
		}
		if(rc != '-')
		{
			r[i] = rc - '0';
			has_father[r[i]] = true; 
		}
	}
	
	int root = 0;
	while(has_father[root])
		root++;
	dfs_reverse(root);
	bfs(root);
	int k = 0;
	dfs(root, k);
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值