判斷給定的二叉樹是否爲二叉排序樹

這是CSDN博主Hackbuteer1的文章!學習一下。


思路:若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
它的左、右子樹也分別爲二叉排序樹。

遞歸遍歷就可以了,反正就是左孩子的key比根節點的key小,右孩子的key比根節點的key大,一旦有不滿足條件的就判定不是。

完整的代碼如下:

  1. #include "stdio.h"  
  2. #include "stdlib.h"  
  3. typedef struct node  
  4. {  
  5.     int data;  
  6.     struct node *lchild,*rchild;  
  7. }Bitree;  
  8. Bitree *B[100];  
  9. Bitree *CreateBiTree()  
  10. {  
  11.     int num,i,n;  
  12.     Bitree *t,*s;  
  13.     t=NULL;  
  14.     printf("建立二叉樹(1表示爲虛結點,0表示輸入結束):/n");  
  15.     num=0;  
  16.     scanf("%d",&n);  
  17.     while(n!=0)  
  18.     {  
  19.         s=(Bitree *)malloc(sizeof(Bitree));  
  20.         s->data=n;  
  21.         s->lchild=s->rchild=NULL;  
  22.         num++;  
  23.         if(!t)  
  24.             t=s;  
  25.         B[num]=s;  
  26.         scanf("%d",&n);  
  27.     }  
  28.     for(i=1;i<=num;i++)  
  29.     {  
  30.         if(B[i]->data!=1)  
  31.         {  
  32.             if(2*i<=num && B[2*i]->data!=1)  
  33.                 B[i]->lchild=B[2*i];  
  34.             if(2*i+1<=num && B[2*i+1]->data!=1)  
  35.                 B[i]->rchild=B[2*i+1];  
  36.         }  
  37.     }  
  38.     return t;  
  39. }  
  40. int IsSearchTree(const Bitree *t)  //遞歸遍歷二叉樹是否爲二叉排序樹  
  41. {  
  42.     if(!t)        //空二叉樹情況  
  43.         return 1;  
  44.     else if(!(t->lchild) && !(t->rchild))   //左右子樹都無情況  
  45.         return 1;  
  46.     else if((t->lchild) && !(t->rchild))    //只有左子樹情況  
  47.     {  
  48.         if(t->lchild->data>t->data)  
  49.             return 0;  
  50.         else  
  51.             return IsSearchTree(t->lchild);  
  52.     }  
  53.     else if((t->rchild) && !(t->lchild))   //只有右子樹情況  
  54.     {  
  55.         if(t->rchild->data<t->data)  
  56.             return 0;  
  57.         else  
  58.             return IsSearchTree(t->rchild);  
  59.     }  
  60.     else         //左右子樹全有情況  
  61.     {                                  
  62.         if((t->lchild->data>t->data) || (t->rchild->data<t->data))  
  63.             return 0;  
  64.         else  
  65.             return ( IsSearchTree(t->lchild) && IsSearchTree(t->rchild) );  
  66.     }  
  67. }  
  68. int main(void)  
  69. {  
  70.     int flag=0;  
  71.     Bitree *tree;  
  72.     tree=CreateBiTree();  
  73.     flag=IsSearchTree(tree);  
  74.     if(flag)  
  75.         printf("這棵樹是二叉排序樹!/n");  
  76.     else  
  77.         printf("這棵樹不是二叉排序樹!/n");  
  78.     system("pause");  
  79.     return 0;  
  80. }  

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章