PAT1043. Is It a Binary Search Tree (25)(BST)

题意:

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

思路:

这题判断是否为BJT很简单和输出后序遍历都很简单,递归一下即可。我做的时候主要是没想到怎么处理镜像。就按照第一个点和第二个点判断大小来做了一下果然有几个点过不去。后来看了一下别人代码,其实很简单,先按BJT处理一遍,如果后序遍历有n个点就说明是BJT,如果没有n个点就再按照镜像处理一遍,如果有n个点说明是镜像,如果两个都不为n就输出NO

#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<sstream>
#include<functional>
#include<algorithm>
using namespace std;
const int INF = 0xfffff;
const int maxn = 1050;
int n;
int tree[maxn];
bool flag = true;
vector<int> res;

void dfs1(int left, int right) {
	if (left > right)
		return;
	int pos;
	for (pos = left+1; pos <= right; pos++) {
		if (tree[pos] >= tree[left])
			break;
	}
	for (int i = pos; i <= right; i++) {
		if (tree[i] < tree[left]) {
			return;
		}
	}
	dfs1(left + 1, pos - 1);
	dfs1(pos, right);
	res.push_back(tree[left]);
}

void dfs2(int left, int right) {
	if (left > right) 
		return;
	int pos;
	for (pos = left + 1; pos <= right; pos++) {
		if (tree[pos] < tree[left])
			break;
	}
	for (int i = pos; i <= right; i++) {
		if (tree[i] >= tree[left]) {
			return;
		}
	}
	dfs2(left + 1, pos - 1);
	dfs2(pos, right);
	res.push_back(tree[left]);
}

int main() {
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> tree[i];
	dfs1(0, n - 1);
	if (res.size()!= n) {
		res.clear();
		dfs2(0, n - 1);
	}
	if (res.size()==n) {
		cout << "YES" << endl << res[0];
		for (int i = 1; i < n; i++)
			cout << " " << res[i];
	} else {
		cout << "NO" << endl;
	}
	return 0;
}

posted @ 2018-04-27 09:32  seasonal  阅读(76)  评论(0编辑  收藏  举报