這是CSDN博主Hackbuteer1的文章!學習一下。
思路:若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
它的左、右子樹也分別爲二叉排序樹。
遞歸遍歷就可以了,反正就是左孩子的key比根節點的key小,右孩子的key比根節點的key大,一旦有不滿足條件的就判定不是。
完整的代碼如下:
- #include "stdio.h"
- #include "stdlib.h"
- typedef struct node
- {
- int data;
- struct node *lchild,*rchild;
- }Bitree;
- Bitree *B[100];
- Bitree *CreateBiTree()
- {
- int num,i,n;
- Bitree *t,*s;
- t=NULL;
- printf("建立二叉樹(1表示爲虛結點,0表示輸入結束):/n");
- num=0;
- scanf("%d",&n);
- while(n!=0)
- {
- s=(Bitree *)malloc(sizeof(Bitree));
- s->data=n;
- s->lchild=s->rchild=NULL;
- num++;
- if(!t)
- t=s;
- B[num]=s;
- scanf("%d",&n);
- }
- for(i=1;i<=num;i++)
- {
- if(B[i]->data!=1)
- {
- if(2*i<=num && B[2*i]->data!=1)
- B[i]->lchild=B[2*i];
- if(2*i+1<=num && B[2*i+1]->data!=1)
- B[i]->rchild=B[2*i+1];
- }
- }
- return t;
- }
- int IsSearchTree(const Bitree *t) //遞歸遍歷二叉樹是否爲二叉排序樹
- {
- if(!t) //空二叉樹情況
- return 1;
- else if(!(t->lchild) && !(t->rchild)) //左右子樹都無情況
- return 1;
- else if((t->lchild) && !(t->rchild)) //只有左子樹情況
- {
- if(t->lchild->data>t->data)
- return 0;
- else
- return IsSearchTree(t->lchild);
- }
- else if((t->rchild) && !(t->lchild)) //只有右子樹情況
- {
- if(t->rchild->data<t->data)
- return 0;
- else
- return IsSearchTree(t->rchild);
- }
- else //左右子樹全有情況
- {
- if((t->lchild->data>t->data) || (t->rchild->data<t->data))
- return 0;
- else
- return ( IsSearchTree(t->lchild) && IsSearchTree(t->rchild) );
- }
- }
- int main(void)
- {
- int flag=0;
- Bitree *tree;
- tree=CreateBiTree();
- flag=IsSearchTree(tree);
- if(flag)
- printf("這棵樹是二叉排序樹!/n");
- else
- printf("這棵樹不是二叉排序樹!/n");
- system("pause");
- return 0;
- }