# 判断一棵树是否为排序二叉树（二叉搜索树）

#include <iostream>
#include<limits>

using namespace std;

typedef struct Btree
{
int num;
struct Btree * lchild;
struct Btree * rchild;
} *PBtree,Btree;

int prev=numeric_limits<int>::min();

//建立一棵排序二叉树
PBtree createtree(PBtree root,int val)
{
PBtree newNode=new Btree();
newNode->lchild=NULL;
newNode->rchild=NULL;
newNode->num=val;

if(root==NULL)
{
root=newNode;
return newNode;
}

while(root!=NULL)
{
PBtree pback=NULL;
PBtree pcur=root;
while(pcur!=NULL)
{
pback=pcur;
if(pcur->num<val)
pcur=pcur->rchild;
else if(pcur->num>val)
pcur=pcur->lchild;
else
{
delete newNode;
return pcur;
}
}

if(pback->num>val)
pback->lchild=newNode;
else
pback->rchild=newNode;
return pback;
}
}

//递归实现先序遍历
void preorder(PBtree root)
{
if(root==NULL)
return ;
cout<<root->num<<" ";
preorder(root->lchild);
preorder(root->rchild);
}

//递归实现中序遍历
void inorder(PBtree root)
{
if(root==NULL)
return ;
inorder(root->lchild);
cout<<root->num<<" ";
inorder(root->rchild);
}

//递归实现后序遍历
void postorder(PBtree root)
{
if(root==NULL)
return ;
postorder(root->lchild);
postorder(root->rchild);
cout<<root->num<<" ";
}

bool judgeBST1(PBtree root)
{
if(root==NULL)
return 1;
else
{
int b=judgeBST1(root->lchild);

if(b==0||prev>=root->num)
return 0;
judgeBST1(root->rchild);
}
}
int main()
{
PBtree root=NULL;
//cout<<prev<<endl;
root=createtree(root,6);
int a[]={1,2,-6,3,-4,7,9,8,10,5};
for(int i=0;i<10;i++)
createtree(root,a[i]);
cout<<judgeBST1(root)<<endl;

inorder(root);

return 0;
}


1
-6 -4 1 2 3 5 6 7 8 9 10