[PAT-A 1102]Invert a Binary Tree

在这里插入图片描述
考察二叉树的遍历

题目大意
二叉树有n个节点(节点编号0-N-1),给出每个节点的左右孩子节点的编号,把该二叉树反转(把每个节点的左右子树都交换),输出反转后二叉树层序遍历序列和中序遍历序列。

思路:
1.给出节点编号的关系,使用二叉树的静态写法。
2.设置isroot数组,找见一个不是所有节点的子节点的节点,即根节点。
3.反转二叉树只需要进行后序遍历,在后序遍历的时候访问根节点时交换lchild和rchild即可。

在输入的时候可以用scnaf("%*c)用以接受换行符(也可以使用getchar())。

AC代码:

//PAT_A 1102
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 110;
struct node {
	int lchild, rchild;
}Node[maxn];
bool notRoot[maxn] = { false };//记录是不是根节点
int n, num = 0;
void print(int id) {
	printf("%d", id);
	num++;
	if (num < n)printf(" ");
	else printf("\n");
}
void inOrder(int root) {
	if (root == -1)return;
	inOrder(Node[root].lchild);
	print(root);
	inOrder(Node[root].rchild);
}
void bfs(int root) {
	queue<int> q;
	q.push(root);
	while (!q.empty()) {
		int now = q.front();
		q.pop();
		print(now);
		if (Node[now].lchild != -1)q.push(Node[now].lchild);
		if (Node[now].rchild != -1)q.push(Node[now].rchild);
	}
}
void postOrder(int root) {//在后序遍历的时候交换左右子树
	if (root == -1)return;
	postOrder(Node[root].lchild);
	postOrder(Node[root].rchild);
	swap(Node[root].lchild, Node[root].rchild);
}
int strToNum(char c) {//这里传进来的全是孩子节点,不可能时根节点
	if (c == '-')return -1;
	else {
		notRoot[c - '0'] = true;//节点c不是根节点
		return c - '0';
	}
}
int findRoot() {
	for (int i = 0; i < n; i++) {
		if (notRoot[i] == false)return i;
	}
}
int main() {
	char lchild, rchild;
	(void)scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		(void)getchar();
		(void)scanf("%c %c", &lchild, &rchild);
		Node[i].lchild = strToNum(lchild);
		Node[i].rchild = strToNum(rchild);
	}
	int root = findRoot();
	postOrder(root);
	bfs(root);
	num = 0;
	inOrder(root);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值