【1043 25 BST】 Is It a Binary Search Tree

传送门

题意

给定一个长度为 \(n\) 序列,判断是不是二叉搜索树的先序序列或者是将左右子树交换的镜像二叉搜索树,如果是输出 YES 和其后序序列,如果不是直接输出 NO

数据范围

\(n\leq 1000\)

题解

  • 根据大小值找到右子树的根,然后判断右子树是否满足,不满足剪枝
  • 对左右子树的序列进行递归,后序遍历最后将根放入序列

Code

#include <bits/stdc++.h>
using namespace std;

vector<int> post;
vector<int> pre;
bool mirror = 0;

void dfs(int l, int r) {
	if (l > r) return;
	int l_root = l + 1;
	int r_root = l_root;
	if (mirror) { // 右边是小的
		while (pre[r_root] >= pre[l] and r_root <= r) r_root++;
		for (int i = r_root; i <= r; i++) {
			if (pre[i] >= pre[l]) return;
		}
	} else {
		while (pre[r_root] < pre[l] and r_root <= r) r_root++;
		for (int i = r_root; i <= r; i++) {
			if (pre[i] < pre[l]) return;
		}
	}
	dfs(l_root, r_root - 1);
	dfs(r_root, r);
	post.push_back(pre[l]);
}
int main() {
	int n; cin >> n;
	pre.resize(n);
	for (auto& it : pre) cin >> it;
	if (pre[0] <= pre[1]) mirror = 1;
	dfs(0, n - 1);
	if (post.size() == pre.size()) {
		cout << "YES" << endl << post[0];
		for (int i = 1; i < post.size(); i++) {
			cout << ' ' << post[i];
		}
	} else {
		cout << "NO";
	}
}
posted @ 2021-02-21 23:34  Hyx'  阅读(66)  评论(0)    收藏  举报