1043. Is It a Binary Search Tree

题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1043

// 之前写建树的代码都不标准
// 本题的思路,参考了同学的思想:
// 如果不符合条件,建树终止,后执行一次遍历,
// 树的节点不足n,则代表建树失败。

#include <stdio.h>
#include <iostream>
#include <vector>

#define SIZE 100000+10
using namespace std;

struct Node
{
	Node *lc;
	Node *rc;
	int value;
};


// normal
Node * build_bin_tree1(int s, int e, vector<int> preorder)
{
	if (s > e) return NULL;

	Node *root = new Node();
	root->value = preorder[s];

	int i;
	for(i = s+1; i<= e; i++)
	{
		if(preorder[i] >= preorder[s])
		{
			break;
		}
	}

	// check
	for(int j = i; j <= e; j++)
	{
		if(preorder[j] < preorder[s])
		{
			return NULL;
		}
	}

	root->lc = build_bin_tree1(s+1, i-1, preorder);
	root->rc = build_bin_tree1(i, e, preorder);

	return root;
}

// mirror
Node * build_bin_tree2(int s, int e, vector<int> preorder)
{
	if (s > e) return NULL;

	Node *root = new Node();
	root->value = preorder[s];

	int i;
	for(i = s+1; i <= e; i++)
	{
		if(preorder[i] < preorder[s])
		{
			break;
		}
	}

	for(int j=i; j<=e; j++)
	{
		if(preorder[j] >= preorder[s])
		{
			return NULL;
		}
	}


	root->lc = build_bin_tree2(s+1, i-1, preorder);
	root->rc = build_bin_tree2(i, e, preorder);

	return root;
}

void post_order(Node * root, vector<int> &postorder)
{
	if(root == NULL)	return;

	post_order(root->lc, postorder);
	post_order(root->rc, postorder);
	postorder.push_back(root->value);
}

void Output(vector<int> order)
{
	int i;
	for(i = 0; i < order.size(); i++)
	{
		printf("%d ", order[i]);
	}
}


int main()
{
	#ifdef ONLINE_JUDGE
	#else
		freopen("E:\\in.txt", "r", stdin);
	#endif

	int n;
	while(scanf("%d", &n) != EOF)
	{
		vector<int> preorder;
		while(n-->0)
		{
			int t;
			scanf("%d", &t);
			preorder.push_back(t);
		}

		//creating tree
		Node * T1 = build_bin_tree1(0, preorder.size()-1, preorder);
		Node * T2 = build_bin_tree2(0, preorder.size()-1, preorder);

		//get postorder
		vector<int> postorder1, postorder2; 
		post_order(T1, postorder1);
		post_order(T2, postorder2);

		//check and output 
		if(postorder1.size() < preorder.size() && postorder2.size() < preorder.size())
		{
			printf("NO\n");
			continue;
		}
		printf("YES\n");
		if(postorder1.size() == preorder.size())
		{
		//	printf("Normal\n");
			int i;
			for(i=0; i<postorder1.size()-1; i++)
			{
				printf("%d ", postorder1[i]);
			}
			printf("%d\n", postorder1[postorder1.size()-1]);
		}
		else if(postorder2.size() == preorder.size())
		{
		//	printf("Mirror\n");
			int i;
			for(i=0; i<postorder2.size()-1; i++)
			{
				printf("%d ", postorder2[i]);
			}
			printf("%d\n", postorder2[postorder2.size()-1]);
		}		
	}// while
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值