L2-004 这是二叉搜索树吗? (25 分)
一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,
其左子树中所有结点的键值小于该结点的键值;
其右子树中所有结点的键值大于等于该结点的键值;
其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
输入格式:
输入的第一行给出正整数 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<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
struct node{
int data;
int lchild, rchild;
}node[N];
int cnt, root = -1;
int newNode(int x){
node[cnt].data = x, node[cnt].lchild = -1, node[cnt].rchild = -1;
return cnt++;
}
void build(int &root, int x){
if (root == -1) {
root = newNode(x);
return;
}
if (x < node[root].data) build(node[root].lchild, x);
else build(node[root].rchild, x);
}
vector<int> pre, post, a;
void preorder(int &root){
if (root == -1)
return;
pre.push_back(node[root].data);
preorder(node[root].lchild);
preorder(node[root].rchild);
}
void postorder(int &root){
if (root == -1)
return;
postorder(node[root].lchild);
postorder(node[root].rchild);
post.push_back(node[root].data);
}
void mirror(int &root){
if (root == -1)
return;
swap(node[root].lchild, node[root].rchild);
mirror(node[root].lchild);
mirror(node[root].rchild);
}
void out(){
bool f = 1;
for (int i = 0; i < a.size(); i++)
if (a[i] != pre[i]) {
f = 0;
break;
}
if (!f) return;
puts("YES");
postorder(root);
for (int i = 0; i < post.size() - 1; i++) printf("%d ", post[i]);
printf("%d\n", post[post.size() - 1]);
exit(0);
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
build(root, x);
a.push_back(x);
}
preorder(root);
out();
mirror(root);
pre.clear();
preorder(root);
out();
puts("NO");
return 0;
}