A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
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.
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.
Sample Input 1:
7
8 6 5 7 10 8 11
Sample Output 1:
YES
5 7 6 8 11 10 8
Sample Input 2:
7
8 10 11 8 6 7 5
Sample Output 2:
YES
11 8 10 7 5 6 8
Sample Input 3:
7
8 6 8 5 10 9 11
Sample Output 3:
NO
题目大意:给定一个序列,判断它是不是一颗BST的前序或镜像前序。如果是,输出YES以及后序或镜像后序;否则,输出NO。
思路:先假设是一颗BST,通过序列来建立这棵树。然后遍历这棵树即可。
代码如下:
#include <iostream>
#include <vector>
using namespace std;
typedef struct node* bst;
struct node
{
int data;
bst left;
bst right;
};
vector<int>v, pre, mir;
bst Insert(bst t, int x)//建树
{
if(!t)
{
t = new node;
t->data = x;
t->left = t->right = NULL;
}
else if(x >= t->data)
t->right = Insert(t->right, x);
else
t->left = Insert(t->left, x);
return t;
}
void preorder(bst t)//前序
{
if(!t) return ;
pre.push_back(t->data);
preorder(t->left);
preorder(t->right);
}
void mirpre(bst t)//镜像前序
{
if(!t) return ;
mir.push_back(t->data);
mirpre(t->right);
mirpre(t->left);
}
void postorder(bst t)//后序
{
if(!t) return ;
postorder(t->left);
postorder(t->right);
v.push_back(t->data);
}
void mirpost(bst t)//镜像后序
{
if(!t) return ;
mirpost(t->right);
mirpost(t->left);
v.push_back(t->data);
}
int main()
{
int n;
cin >> n;
bst t = NULL;
int i;
for(i=0;i<n;i++)
{
int x;
cin >> x;
v.push_back(x);
t = Insert(t, x);
}
preorder(t);
mirpre(t);
if(v == pre)
{
cout << "YES" <<endl;
v.clear();
postorder(t);
cout << v[0];
for(i=1; i<v.size(); i++)
cout << " " << v[i];
}
else if(v == mir)
{
cout << "YES" <<endl;
v.clear();
mirpost(t);
cout << v[0];
for(i=1; i<v.size(); i++)
cout << " " << v[i];
}
else cout << "NO";
cout << endl;
return 0;
}
总结
- 今天才知道vector是可以直接判断是否相等的。。
- 关于BST的题,有时候题目会说左子树小于等于根,有时候题目会说右子树大于等于根。要注意等于是在哪边。