データ構造の実践-ツリーを並べ替えますか?


本稿は[データ構造基礎シリーズ(8):検索]の実践プロジェクトの参考です.
【アイテム-ツリーを並べ替えますか?】与えられたツリーがツリーソートツリーであるかどうかを判断するアルゴリズムを設計します.
[参考解答]int JudgeBST()は設計されたアルゴリズムに対応した実装である.
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef int KeyType;                    //       
typedef char InfoType;
typedef struct node                     //    
{
    KeyType key;                        //    
    InfoType data;                      //     
    struct node *lchild,*rchild;        //      
} BSTNode;
int path[MaxSize];                      //    ,      
void DispBST(BSTNode *b);               //    
int InsertBST(BSTNode *&p,KeyType k)    //  *p     BST         k   
{
    if (p==NULL)                        //    ,           
    {
        p=(BSTNode *)malloc(sizeof(BSTNode));
        p->key=k;
        p->lchild=p->rchild=NULL;
        return 1;
    }
    else if (k==p->key)
        return 0;
    else if (k<p->key)
        return InsertBST(p->lchild,k);  //   *p     
    else
        return InsertBST(p->rchild,k);  //   *p     
}
BSTNode *CreatBST(KeyType A[],int n)
//   A              
{
    BSTNode *bt=NULL;                   //   bt   
    int i=0;
    while (i<n)
        InsertBST(bt,A[i++]);       // A[i]       T 
    return bt;                          //              
}

void DispBST(BSTNode *bt)
//             bt
{
    if (bt!=NULL)
    {
        printf("%d",bt->key);
        if (bt->lchild!=NULL || bt->rchild!=NULL)
        {
            printf("(");
            DispBST(bt->lchild);
            if (bt->rchild!=NULL) printf(",");
            DispBST(bt->rchild);
            printf(")");
        }
    }
}

/* int JudgeBST(BSTNode *bt)                       */
KeyType predt=-32767; //predt     ,            ,   -∞
int JudgeBST(BSTNode *bt)   //  bt   BST
{
    int b1,b2;
    if (bt==NULL)
        return 1;    //          
    else
    {
        b1=JudgeBST(bt->lchild);   //         ,        0,    1
        if (b1==0 || predt>=bt->key)  //          ,     (    )        
            return 0;    //  “       ”
        predt=bt->key;   //              
        b2=JudgeBST(bt->rchild);   //        
        return b2;
    }
}

int main()
{
    BSTNode *bt;
    int a[]= {43,91,10,18,82,65,33,59,27,73},n=10;
    printf("       :");
    bt=CreatBST(a,n);
    DispBST(bt);
    printf("
"
); printf("bt%s
"
,(JudgeBST(bt)?" BST":" BST")); bt->lchild->rchild->key = 30; // ! printf(" :"); DispBST(bt); printf("
"
); printf("bt%s
"
,(JudgeBST(bt)?" BST":" BST")); return 0; }