二叉排序树的判定

【问题描述】课后作业第6题。试写一个判别给定二叉树是否为二叉排序树的算法。以前序遍历序列和中序遍历序列给出该二叉树的结点,并创建该二叉树。然后再进行判断。请注意,树中结点关键字可能相同。

【样例输入1】

6 4 5 8 6 9 0

4 5 6 6 8 9 0
【样例输出1】

true

【样例输入2】

6 4 7 8 0

4 7 6 8 0
【样例输出2】

false

【提示】若直接根据给定的中序是否有序来进行判断,此种判断方法不得分。务必先创建二叉树的链式存储,再对其进行判断。

#include<bits/stdc++.h>
#define max 100
using namespace std;
int pre[max];
int in[max];
typedef struct BiNode
{
    int date;
    BiNode*LChild;
    BiNode*RChild;
}*BiTree;
int getMin(BiTree root)
{
    BiNode*temp=root;
    while(temp->LChild!=NULL) temp=temp->LChild;
    return temp->date;
}
int getMax(BiTree root)
{
    BiNode*temp=root;
    while(temp->RChild!=NULL) temp=temp->RChild;
    return temp->date;
}
bool checkBST(BiTree root)
{
    if(root==NULL) return true;
    else
    {
        if(root->LChild!=NULL&&root->date<=getMax(root->LChild)) return false;
        if(root->RChild!=NULL&&root->date>getMin(root->RChild)) return false;
        return checkBST(root->LChild)&&checkBST(root->RChild);
    }
}
void  CreateBiTree(BiTree &root,int preLeft, int preRight, int inLeft, int inRight)
{
	if (preLeft > preRight)  root=NULL;
	else
	{
		root = new BiNode;
		int mid = -1;
		for (int i = inLeft; i <= inRight; i++)
		{
			if (in[i] == pre[preLeft])
			{
				mid = i;
				break;
			}
		}
		root->date = in[mid];
		CreateBiTree(root->LChild,preLeft + 1, preLeft + mid - inLeft, inLeft, mid - 1);
		CreateBiTree(root->RChild,preRight + mid - inRight + 1, preRight, mid + 1, inRight);
	}
}
int main()
{
    for(int i=0;i<max;i++)
    {
        int v;
        cin>>v;
        pre[i]=v;
        if(v==0) break;
    }
     for(int i=0;i<max;i++)
    {
        int v;
        cin>>v;
        in[i]=v;
        if(v==0) break;
    }
    int preLeft=0;int preRight=0;int inLeft=0;int inRight;
    for(int i=0;i<max;i++)
    {
        if(pre[i]!=0)
        {
            preRight++;
        }
        else break;
    }
    preRight=preRight-1;
    inRight=preRight;
    BiTree root=new BiNode;
    CreateBiTree(root,preLeft,preRight,inLeft,inRight);
    if(checkBST(root)) cout<<"true"<<endl;
    else cout<<"false"<<endl;
    return 0;
}
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值