2023pat甲级春季考试最后一题

文章讲述了如何使用C++编程解决二叉树的构建、前序遍历、后序遍历以及判断二叉树是否为镜像的问题。通过输入的后序遍历和中序遍历序列构建二叉树,然后检查其对称性。同时,展示了前序遍历和后序遍历的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题考试的时候真的整麻了,不知道怎么判断对错,后来查了一下资料才焕然大悟,还是太菜了,记录一下,就当是补充知识了

在这里插入图片描述
在这里插入图片描述

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define  N  110
int n, m;
int post[N], in[N];
vector<int>ans1, ans2;
int leftnum, rightnum = 0;
struct node
{
	int data;
	node* lchild;
	node* rchild;
};
bool arrvie_bottom_left = false;
bool arrvie_bottom_right = false;
node* Create(int postL, int postR, int inL, int inR)
{
	if (postL > postR)return nullptr;
	node* root = new node;
	root->data = post[postR];
	int k;
	for (k = inL; k < inR; k++)
	{
		if (in[k] == post[postR])break;
	}
	int numLeft = k - inL;
	root->lchild = Create(postL, postL + numLeft - 1, inL, k - 1);
	root->rchild = Create(postL + numLeft, postR - 1, k + 1, inR);
	return root;
}
void PreOrder(node* root)
{
	if (root == NULL)
	{
		arrvie_bottom_left = true;
		leftnum = ans1[ans1.size() - 1];
		return;
	}
	if (!arrvie_bottom_left)
	{
		cout << root->data << " ";
		ans1.push_back(root->data);
		PreOrder(root->lchild);
		PreOrder(root->rchild);
	}


}

void dfs(node* root)
{
	if (root->lchild == NULL && root->rchild == NULL && root->data != leftnum && root->data != rightnum)
	{
		ans1.push_back(root->data);
		cout << root->data << " ";
	}
	if (root->lchild != NULL)
	{
		dfs(root->lchild);
	}
	if (root->rchild != NULL)
	{
		dfs(root->rchild);
	}

}
void PostOrder(node* root)
{
	if (root == NULL)
	{
		arrvie_bottom_right = true;
		return;
	}
	if (!arrvie_bottom_right)
	{
		//cout << root->data << " ";
		ans2.push_back(root->data);
		PostOrder(root->rchild);
		PostOrder(root->lchild);
	}

}

/*
27
5 4 6 22 3 23 7 20 2 21 8 18 9 1 10 19 11 24 17 25 12 26 16 27 13 15 14
5 6 22 4 7 23 20 3 8 21 9 18 2 10 11 24 19 12 26 25 13 27 14 15 16 17 1 

11
4 8 10 2 5 1 6 3 9 11 7
10 8 4 5 2 6 11 9 7 3 1
*/

bool is_Mirror(node*root1,node*root2)
{
	if (root1==NULL&&root2==NULL)return true;
	if (root1 == NULL || root2 == NULL)return false;
	return is_Mirror(root1->lchild,root2->rchild)&&is_Mirror(root1->rchild,root2->lchild);
}

bool is_symmetry(node*root)
{
	if (root==NULL)return true;
	else is_Mirror(root,root);
}
int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> in[i];
	}
	for (int i = 0; i < n; i++)
	{
		cin >> post[i];
	}
	node* root = Create(0, n - 1, 0, n - 1);
	//cout << "Yes" << endl;
	if(is_symmetry(root))cout << "Yes" << endl;
	else cout << "No" << endl;
	PreOrder(root);
	dfs(root);
	PostOrder(root);
	ans2.erase(ans2.begin());
	reverse(ans2.begin(), ans2.end());
	cout << ans2[1];
	for (int i = 2; i < ans2.size(); i++)
	{
		cout << " " << ans2[i];
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值