# PAT 解题报告 1043. Is It a Binary Search Tree (25)

### 1043. Is It a Binary Search Tree 题目描述：

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

• The left subtree of a node contains only nodes with keys less than the node’s key.
• The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
• Both the left and right subtrees must also be binary search trees.

If we swap the left and right subtrees of every node, then the resulting tree is called the Mirror Image of a BST.

Now given a sequence of integer keys, you are supposed to tell if it is the preorder traversal sequence of a BST or the mirror image of a BST.

### 1043. Is It a Binary Search Tree 算法分析：

```#include <iostream>
#include <sstream>

#include <cstring>
#include <cstdio>
#include <cmath>

#include <algorithm>
#include <string>
#include <vector>

#define REP(i,n) for(int i=0;i<(n);++i)

using namespace std;

struct Node {
int val;
Node *left;
Node *right;
};

bool flag;
int N;
int ele[1008];
Node *tree;

void init(Node *t) {
t->val = 0;
t->left = NULL;
t->right = NULL;
}

Node *build(int l, int r) {
if(l > r) return NULL;

Node *root = new Node;
init(root);
root->val = ele[l];

if(l == r) return root;

int mid = l+1;
for(int i=l+1; i<=r; ++i) {
if(ele[i] >= ele[l]) {
mid = i;
break;
}
mid++;
}
for(int i=mid; i<=r; ++i) {
if(ele[i]<ele[l]) {
flag = false;
return NULL;
}
}
root->left = build(l+1, mid-1);
root->right = build(mid, r);

return root;
}

//mirror
Node *build2(int l, int r) {
if(l > r) return NULL;

Node *root = new Node;
init(root);
root->val = ele[l];
if(l == r) return root;

int mid = l+1;
for(int i=l+1; i<=r; ++i) {
if(ele[i] < ele[l]) {
mid = i;
break;
}
mid++;
}
for(int i=mid; i<=r; ++i) {
if(ele[i] >= ele[l]) {
flag = false;
return NULL;
}
}
root->left = build2(l+1, mid-1);
root->right = build2(mid, r);

return root;
}

ostringstream oss;

void dfs(Node *r) {
if(NULL == r) return ;
dfs(r->left);
dfs(r->right);
oss<<' '<<r->val;
}

void gao() {
if(0 == N) return;
if(1 == N) {
cout<<"YES"<<endl;
cout<<ele[0]<<endl;
return;
}

flag = true;
tree = new Node;
init(tree);
tree = build(0, N-1);
if(flag) {
cout<<"YES"<<endl;
dfs(tree);
cout<<oss.str().substr(1)<<endl;
return ;
}
flag = true;
tree = new Node;

init(tree);
tree = build2(0, N-1);

if(flag) {
cout<<"YES"<<endl;
dfs(tree);
cout<<oss.str().substr(1)<<endl;
return ;
}
cout<<"NO"<<endl;
return ;
}

int main(void) {
cin>>N;
REP(i, N) cin>>ele[i];
gao();
return 0;
}
```

### 1043. Is It a Binary Search Tree  注意点：

Written on January 18, 2014