一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
- 其左子树中所有结点的键值小于该结点的键值;
- 其右子树中所有结点的键值大于等于该结点的键值;
- 其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
输入格式:
输入的第一行给出正整数 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
#include <iostream>
#include <vector>
using namespace std;
int a[1001], mirror;
vector<int>tree;
void build(int low, int hight) {
if (low > hight) return;
int i = low + 1, j = hight;
if (mirror) {
while (i <= hight && a[low] <= a[i])++i;
while (j > low&& a[low] > a[j])--j;
}
else {
while (i <= hight && a[low] > a[i])++i;
while (j > low&& a[low] <= a[j])--j;
}
if (i - j != 1)return;
build(low + 1, j);
build(i, hight);
tree.push_back(a[low]);
}
int main() {
int N;
cin >> N;
for (int i = 0; i < N; ++i)
cin >> a[i];
build(0, N - 1);
if (tree.size() != N) {
tree.clear();
mirror = 1;
build(0, N - 1);
}
if (tree.size() == N) {
cout << "YES" << endl << tree[0];
for (int i = 1; i < N; ++i)
cout << " " << tree[i];
}
else
cout << "NO";
return 0;
}
下面是自己写的17分代码:测试点3,4,5没过。还没想好bug出在哪儿
#include <iostream>
using namespace std;
struct Node {
int data;
Node* lc, * rc;
};
int flag = 0, mirror = 0;
Node* buildTree(int* a, int n, int mirror) {
if (n == 0)
return NULL;
Node* T = new Node;
T->data = *a;
if (mirror)
T->lc = buildTree(a + 1, n / 2,mirror),
T->rc = buildTree(a + 1 + n / 2, (n - 1) / 2, mirror);
else
T->rc = buildTree(a + 1, n / 2, mirror),
T->lc = buildTree(a + 1 + n / 2, (n - 1) / 2, mirror);
return T;
}
void print(Node* T, int mirror) {
if (T) {
if (mirror)
print(T->lc, mirror),
print(T->rc, mirror);
else
print(T->rc, mirror),
print(T->lc, mirror);
cout << (flag ? " " : "") << T->data;
flag++;
}
}
int judge(Node* T) {
if (T->lc) {
if (T->data < T->lc->data)return 0;
return judge(T->lc);
}
if (T->rc) {
if (T->data > T->rc->data)return 0;
return judge(T->rc);
}
return 1;
}
int main() {
int N, a[1000];
cin >> N;
for (int i = 0; i < N; ++i)
cin >> a[i];
Node* T1 = buildTree(a, N, 0);
Node* T2 = buildTree(a, N, 1);
if (judge(T1)) {
cout << "YES" << endl;
print(T1, 0);
flag++;
}
else if (judge(T2)) {
cout << "YES" << endl;
print(T2, 1);
}
else
cout << "NO";
return 0;
}