天梯赛L2-004 这是二叉搜索树吗? (25 分)

L2-004 这是二叉搜索树吗? (25 分)
一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,

  • 其左子树中所有结点的键值小于该结点的键值;
  • 其右子树中所有结点的键值大于等于该结点的键值;
  • 其左右子树都是二叉搜索树。

所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。

给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。

输入格式:
输入的第一行给出正整数 N(≤1000)。随后一行给出 N 个整数键值,其间以空格分隔。

输出格式:
如果输入序列是对一棵二叉搜索树或其镜像进行前序遍历的结果,则首先在一行中输出 YES ,然后在下一行输出该树后序遍历的结果。数字间有 1 个空格,一行的首尾不得有多余空格。若答案是否,则输出 NO。

输入样例 1:

7
8 6 5 7 10 8 11

输出样例 1:

YES
5 7 6 8 11 10 8

输入样例 2:

7
8 10 11 8 6 7 5

输出样例 2:

YES
11 8 10 7 5 6 8

输入样例 3:

7
8 6 8 5 10 9 11

输出样例 3:

NO

需要注意的点
C++中两个vector是否相等可以直接用 == 来表示,所以我们可以用vector存先序,镜像先序,后序,镜像后序,以达到目的
先构造二叉排序树,再求序列。最后判断并输出

#include <iostream>
#include <vector>
using namespace std;
struct Node
{
	int data;
	Node* lchild;
	Node* rchild;
};
const int maxn = 1010;
int n;
vector<int> num;
vector<int> preOrderList, preOrderMirrorList,postOrderList,postOrderMirrorList;
Node* newNode(int n)
{
	Node* node = new Node;
	node->data = n;
	node->lchild = NULL;
	node->rchild = NULL;
	return node;
}
void insert(Node*& root,int n)
{
	if (root == NULL)
	{
		root = newNode(n);
		return;
	}
	if (n < root->data)
		insert(root->lchild, n);
	else
		insert(root->rchild, n);
	
}
Node* onCreate()
{
	Node* root = NULL;
	for (int i = 0; i < n; i++)
		insert(root, num[i]);
	
	
	return root;
}

void postOrder(Node* root)
{
	if (root == NULL)
		return;
	postOrder(root->lchild);
	postOrder(root->rchild);
	postOrderList.push_back(root->data);
}

void postOrderMirror(Node* root)
{
	if (root == NULL)
		return;
	postOrderMirror(root->rchild);
	postOrderMirror(root->lchild);
	postOrderMirrorList.push_back(root->data);
}

void preOrder(Node* root)
{
	if (root == NULL)
		return;
	preOrderList.push_back(root->data);
	preOrder(root->lchild);
	preOrder(root->rchild);
}

void preOrderMirror(Node* root)
{
	if (root == NULL)
		return;
	preOrderMirrorList.push_back(root->data);
	preOrderMirror(root->rchild);
	preOrderMirror(root->lchild);
}
/*void print(Node* root)
{
	if (root == NULL)
		return;
	cout << root->data << " ";
	print(root->lchild);
	print(root->rchild);
}*/

int main()
{
	Node* root = NULL;
	int temp;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> temp;
		num.push_back(temp);
	}
	root = onCreate();
//	print(root);
	preOrder(root);
	preOrderMirror(root);
	if (num == preOrderList)
	{
		cout << "YES" << endl;
		postOrder(root);
		for (int i = 0; i < n; i++)
		{
			cout << postOrderList[i];
			if (i != n - 1)
				cout << " ";
		}
	}
	else if (num == preOrderMirrorList)
	{
		cout << "YES" << endl;
		postOrderMirror(root);
		for (int i = 0; i < n; i++)
		{
			cout << postOrderMirrorList[i];
			if (i != n - 1)
				cout << " ";
		}
	}
	else
		cout << "NO";
	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值