1043 Is It a Binary Search Tree (25 分)
…
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N integer keys are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, first print in a line YES if the sequence is the preorder traversal sequence of a BST or the mirror image of a BST, or NO if not. Then if the answer is YES, print in the next line the postorder traversal sequence of that tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
思路:
- 先根据给出数据建立二叉搜索树
- 假设给出序列是BST的前序,将给出序列与建立的二叉搜索树前序序列比较
- 如果相等说明正确,输出后序排列。不等则比较是否为镜像二叉树,相等输出后序排列,不等则说明给出数据不是BST,输出NO。
#include <stdio.h>
#include <vector>
using namespace std;
struct node
{
int data; /* 数据域 */
node* lchild, *rchild; /* 指针域 */
};
void insert(node* &root, int data) {
if (root == NULL) { /*当到达空节点时,即为需要插入的位置*/
root = new node;
root->data = data;
root->lchild = root->rchild = NULL;
}
else if (root->data > data) insert(root->lchild, data);
else insert(root->rchild, data);
}
void preordered(node* root, vector<int>&vi) { /*前序*/
if(root == NULL) return;
vi.push_back(root->data);
preordered(root->lchild, vi);
preordered(root->rchild, vi);
}
void premordered(node* root, vector<int>&vi) { /*镜像前序*/
if(root == NULL) return;
prem.push_back(root->data);
premordered(root->rchild, vi);
premordered(root->lchild, vi);
}
void postordered(node* root, vector<int>&vi) { /*后序*/
if(root == NULL) return;
postordered(root->lchild, vi);
postordered(root->rchild, vi);
vi.push_back(root->data);
}
void postmordered(node* root, vector<int>&vi) { /*镜像后序*/
postmordered(root->rchild, vi);
postmordered(root->lchild, vi);
vi.push_back(root->data);
}
vector<int>origin, pre, prem, post, postm; /*使用vector可以直接比较,不需要for循环*/
int main() {
int n,a;
scanf("%d", &n);
node* root = NULL;
for (int i = 0; i < n; i++) { /*建立BST*/
scanf("%d", &a);
origin.push_back(a);
insert(root, a);
}
preordered(root, pre);
premordered(root, prem);
if (pre == origin) { /*是否为BST*/
printf("YES\n");
postordered(root, post);
for (int i = 0; i < post.size(); i++) {
printf("%d", post[i]);
if (i != post.size() - 1) printf(" "); /*格式*/
}
}
else if (prem == origin) {/*是否为镜像BST*/
printf("YES\n");
postmordered(root, postm);
for (int i = 0; i < postm.size(); i++) {
printf("%d", postm[i]);
if (i != postm.size() - 1) printf(" ");
}
}
else printf("NO\n");
return 0;
}