0
点赞
收藏
分享

微信扫一扫

PAT A1043

洛茄 2022-02-18 阅读 32

镜像树的创建即在插入insert函数中将原本向左右子树递归的条件交换一下即可

void insert1(node* &root,int v)
{
	if(root==NULL)//没找到,说明要插入
	{
		root=new_node(v);
		return;
	}
	if(v>=root->data) insert1(root->rchild,v);
	else insert1(root->lchild,v);
}
void insert2(node* &root,int v)//生成镜像树
{
	if(root==NULL)//没找到,说明要插入
	{
		root=new_node(v);
		return;
	}
	if(v<root->data) insert2(root->rchild,v);//只需要反过来即可
	else insert2(root->lchild,v);
}

完整代码如下

#include<bits/stdc++.h>
using std::cin;
using std::cout;
using std::endl;
using std::string;
struct node
{
	int data;
	node *lchild,*rchild;
};
int pre[1005],post[1005];
node* new_node(int v)//新建一个权值为v的结点
{
	node *new_node=new node;
	new_node->data=v;
	new_node->lchild=new_node->rchild=0;
	return new_node;
}
void insert1(node* &root,int v)
{
	if(root==NULL)//没找到,说明要插入
	{
		root=new_node(v);
		return;
	}
	if(v>=root->data) insert1(root->rchild,v);
	else insert1(root->lchild,v);
}
void insert2(node* &root,int v)//生成镜像树
{
	if(root==NULL)//没找到,说明要插入
	{
		root=new_node(v);
		return;
	}
	if(v<root->data) insert2(root->rchild,v);//只需要反过来即可
	else insert2(root->lchild,v);
}
node* create1(int a[],int n)//建树
{
	node *root=NULL;
	for(int i=0;i<n;i++) 
	{
		insert1(root,a[i]);
	}
	return root;
}
node* create2(int a[],int n)//建镜像树
{
	node *root=NULL;
	for(int i=0;i<n;i++) 
	{
		insert2(root,a[i]);
	}
	return root;
}
node* find_min(node *root)//以root为根结点查找子树中最小的结点,查找root的后继应该使用find_min(root->rchild);
{
	while(root->lchild!=NULL)
	{
		root=root->lchild;
	}
	return root;
}
node* find_max(node *root)//以root为根结点查找子树中最大的结点,查找root的前驱应该使用find_max(root->lchild);
{
	while(root->rchild!=NULL)
	{
		root=root->rchild;
	}
	return root;
}
int sum1,sum2;
void pre_order(node *root)
{
	if(root==NULL) return;
//	printf("%d ",root->data);
	pre[sum1++]=root->data;
	pre_order(root->lchild);
	pre_order(root->rchild);
}
void post_order(node *root)
{
	if(root==NULL) return;
	post_order(root->lchild);
	post_order(root->rchild);
	post[sum2++]=root->data;
}
void windows_cmd_support_utf8(void)
{
	#ifdef WIN32
	    system("chcp 65001 & cls");
	#endif
}
int n;
bool compare(int a[],int b[])
{
	for(int i=0;i<n;i++)
	{
		if(a[i]!=b[i]) return false;
	}
	return true;
}
signed main(void)
{
	windows_cmd_support_utf8();
	int a[1005];
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	node *root1=new node;
	root1=create1(a,n);
	pre_order(root1);
	if(compare(a,pre)==true)
	{
		printf("YES\n");
		post_order(root1);
		for(int i=0;i<n-1;i++)
		printf("%d ",post[i]);
		printf("%d",post[n-1]);
		return 0;
	}
	else if(compare(a,pre)==false)
	{
		sum1=0;
		sum2=0;
		node *root2=new node;
		root2=create2(a,n);
		pre_order(root2);
		if(compare(a,pre)==true)
		{
			printf("YES\n");
			post_order(root2);
			for(int i=0;i<n-1;i++)
			printf("%d ",post[i]);
			printf("%d",post[n-1]);
			return 0;
		}
		else
		{
			printf("NO\n");
			return 0;
		}
	}
	return 0;
}
举报

相关推荐

0 条评论