1043

#include<iostream>
#include<vector>
using namespace std;
typedef struct node
{
	int v;
	struct node *left;
	struct node *right;
}Node, *TreeNode;
TreeNode Insert1(TreeNode P, int a);
TreeNode Insert2(TreeNode P, int a);
void PreOrder(TreeNode P,vector<int> &B);
void PostOrder(TreeNode P, vector<int> &C);
int main()
{
	


		int n;
		cin >> n;
		vector<int> A, B, C;
		TreeNode T1, T2;
		T1 = T2 = NULL;
		for (int i = 0; i < n; i++)
		{
			int a;
			cin >> a;
			A.push_back(a);
			T1 = Insert1(T1, a);
			T2 = Insert2(T2, a);
		}
		PreOrder(T1, B);
		PreOrder(T2, C);
		if (A == B)
		{
			cout << "YES" << endl;
			vector<int> ans;
			PostOrder(T1, ans);
			for (int i = 1; i <= n; i++)
			{
				if (i == n)
					cout << ans[i-1] << endl;
				else
					cout << ans[i-1] << ' ';
			}
		}
		else if (A == C)
		{
			cout << "YES" << endl;
			vector<int> ans;
			PostOrder(T2, ans);
			for (int i = 1; i <= n; i++)
			{
				if (i == n)
					cout << ans[i-1] << endl;
				else
					cout << ans[i-1] << ' ';
			}
		}
		else
			cout << "NO" << endl;
	
	system("pause");
	return 0;
}
void PostOrder(TreeNode P, vector<int> &C)
{
	if (P)
	{
		PostOrder(P->left, C);
		PostOrder(P->right, C);
		C.push_back(P->v);
	}
}
void PreOrder(TreeNode P, vector<int> &B)
{
	if (P)
	{
		B.push_back(P->v);
		PreOrder(P->left, B);
		PreOrder(P->right, B);
	}

}
TreeNode Insert1(TreeNode P, int a)
{
	if (!P)
	{
		TreeNode node = new Node();
		node->left = node->right = NULL;
		node->v = a;
		P = node;
	}
	else
	{
		if (a < P->v)
			P->left = Insert1(P->left, a);
		else
			P->right = Insert1(P->right, a);
	}
	return P;
}
TreeNode Insert2(TreeNode P, int a)
{
	if (!P)
	{
		TreeNode node = new Node();
		node->left = node->right = NULL;
		node->v = a;
		P = node;
	}
	else
	{
		if (a >= P->v)
			P->left = Insert2(P->left, a);
		else
			P->right = Insert2(P->right, a);
	}
	return P;
}
发布了195 篇原创文章 · 获赞 9 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/zero_1778393206/article/details/87937130