您的位置:首页 > 其它

浙大PAT (Advanced Level) Practise 1043 Is It a Binary Search Tree (25)

2014-11-07 23:18 381 查看
#include <cstdio>
#include <vector>
using namespace std;

/*根据题意,二叉查找数的左子树节点的所有数值都小于根节点,右子树数值都大于或等于根节点数值。
又输入的一行数字为二叉查找树的先序遍历,因此,对于某一数组num,设其后续遍历为postOrder,可以采
用如下步骤可递归确定该树是否为二叉查找树(同时获取其后续遍历):
1.输入数组的第一个数是根节点(先序遍历的性质);
2.从数组从后往前找到第一个小于根节点数值的数的下标k;k左边(含k)为左子树,右边为右子树。
将根节点数值放入postOrder末尾;
3.递归判断左子树、右子树,同时获取他们的后序遍历序列。
类似的,可以判断镜像二叉查找树,并获取其后序遍历序列。*/
bool isBST(const vector<int> &num, int l, int r, vector<int> &postOrder)//判断二叉查找树
{
if(l == r){//数组只有一个数字
postOrder.insert(postOrder.begin(),num[l]);
return true;
}
if(l == r-1){//数组只有两个数字
postOrder.insert(postOrder.begin(),num[l]);
postOrder.insert(postOrder.begin(),num[r]);
return true;
}
int k = r;
while(num[l] <= num[k] && k > l) --k;
if(k == l){
postOrder.insert(postOrder.begin(),num[l]);
return isBST(num, l+1, r, postOrder);
}
else if(k == r){
for(int i = l + 1; i < r + 1; ++i){
if(num[l] <= num[i]) return false;//左子树中有大于等于根节点的数值
}
postOrder.insert(postOrder.begin(),num[l]);
return isBST(num, l+1, r, postOrder);
}
else{
for(int i = l + 1; i < k + 1; ++i){
if(num[l] <= num[i]) return false;//左子树中有大于等于根节点的数值
}
postOrder.insert(postOrder.begin(),num[l]);
return isBST(num, k+1, r, postOrder) && isBST(num, l+1, k, postOrder);//递归判断左右子树
}
}

bool isMIBST(const vector<int> &num, int l, int r, vector<int> &postOrder)//判断镜像二叉查找树
{
if(l == r){
postOrder.insert(postOrder.begin(),num[l]);
return true;
}
if(l == r-1){
postOrder.insert(postOrder.begin(),num[l]);
postOrder.insert(postOrder.begin(),num[r]);
return true;
}
int k = r;
while(num[l] > num[k] && k > l) --k;
if(k == l){
postOrder.insert(postOrder.begin(),num[l]);
return isMIBST(num, l+1, r, postOrder);
}
else if(k == r){
for(int i = l + 1; i < r + 1; ++i){
if(num[l] > num[i]) return false;
}
postOrder.insert(postOrder.begin(),num[l]);
return isMIBST(num, l+1, r, postOrder);
}
else{
for(int i = l + 1; i < k + 1; ++i){
if(num[l] > num[i]) return false;
}
postOrder.insert(postOrder.begin(),num[l]);
return isMIBST(num, k+1, r, postOrder) && isMIBST(num, l+1, k, postOrder);
}
}

int main()
{
//freopen("in.txt","r",stdin);
int n;
scanf("%d",&n);
int tmp;
vector<int> num;
vector<int> postOrder;//用来存储后续遍历序列
while(n > 0){
scanf("%d", &tmp);
num.push_back(tmp);
--n;
}
bool res = isBST(num, 0, num.size()-1, postOrder);
if(res){
printf("YES\n");
for(int i = 0; i < postOrder.size(); ++i){
if(i != 0) printf(" ");
printf("%d", postOrder[i]);
}
}
else{
postOrder.clear();
res = isMIBST(num, 0, num.size()-1, postOrder);
if(res){
printf("YES\n");
for(int i = 0; i < postOrder.size(); ++i){
if(i != 0) printf(" ");
printf("%d", postOrder[i]);
}
}
else{
printf("NO");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: