【问题描述】课后作业第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;
}