数据结构暑期自学--MOOC浙江大学pta(7-28 搜索树判断)

7-28 搜索树判断

题目链接

关键点:

1、建二叉树,根据输入的先序遍历直接插入,如果为根节点,那么创建空间,初始化左右子树,如果不为,那么就将当前datax和当前结点的data比较,大于则插入左子树,小于插入右子树

2、建好树,之后开始先序遍历该二叉树,比较和当前给出数组是否相同,如果不通,就比较和镜像的先序是否相同

3、镜像先序:则将先序的跟左右,改为跟右左

镜像后序:将后序的左右跟,改为右左根

完整代码:

# include <iostream>
# include <algorithm>
# include <vector>
using namespace std;
vector<int> v1, v2, v3, v4;
int N;
int A[1010];
typedef struct TNode *PtrTree;
struct TNode{
	int data;
	PtrTree Left;
	PtrTree Right;
};
PtrTree Insert(PtrTree root, int x)
{
	if (root == NULL)
	{
		root = (PtrTree)malloc(sizeof(struct TNode));
		root->data = x;
		root->Left = NULL;
		root->Right = NULL;
		return root;
	}
	if (root->data > x)
	root->Left = Insert(root->Left, x);
	else if (root->data <= x)
	root->Right = Insert(root->Right, x);
	else
	return NULL;
	return root;
}

PtrTree CreateTree(PtrTree root, int A[])
{
	root = NULL;
	for (int i=0; i<N; i++)
	{
		root = Insert(root, A[i]);
	}
	return root;
}

void Pre1(PtrTree root)
{
	if (root!=NULL)
	{
		int temp = root->data;
		v1.push_back(temp);
		Pre1(root->Left);
		Pre1(root->Right);
	}
}

void Pro1(PtrTree root)
{
	if (root != NULL)
	{
		Pro1(root->Left);
		Pro1(root->Right);
		int temp = root->data;
		v2.push_back(temp);
	}
}

void Pre2(PtrTree root)
{
	if (root!=NULL)
	{
		int temp = root->data;
		v3.push_back(temp);
		Pre2(root->Right);
		Pre2(root->Left);
	}
}

void Pro2(PtrTree root)
{
	if (root != NULL)
	{
		Pro2(root->Right);
		Pro2(root->Left);
		int temp = root->data;
		v4.push_back(temp);
	}
}

int judgement(int A[], vector<int>&v)
{
	for (int i=0; i<N; i++)
	{
		if (A[i]!=v[i])
		return 0;
	}
	return 1;
}

int main()
{
	cin>>N;
	for (int i=0; i<N; i++)
	cin>>A[i];
	PtrTree root;
	root = CreateTree(root, A);
	
	Pre1(root);
	int flag1 = judgement(A, v1);
	if (flag1 == 1)
	{
		cout<<"YES"<<endl;
		Pro1(root);
		for (int i=0; i<N; i++)
		{
			if (i<N-1)
			cout<<v2[i]<<" ";
			else
			cout<<v2[i];
		}
	}
	else
	{
		Pre2(root);
		int flag2 = judgement(A, v3);
		if (flag2 == 1)
		{
			cout<<"YES"<<endl;
			Pro2(root);
			for (int i=0; i<N; i++)
			{
				if (i<N-1)
				cout<<v4[i]<<" ";
				else
				cout<<v4[i];
			}
		}
		else
		cout<<"NO"<<endl;
	}
	
	
	
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值