第十四周项目3-是否二叉排序树?
来源:互联网 发布:靠谱的美国代购淘宝店 编辑:程序博客网 时间:2024/06/06 15:39
问题:
代码:- #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)
- {
- 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);
- else
- return InsertBST(p->rchild,k);
- }
- BSTNode *CreatBST(KeyType A[],int n)
-
- {
- BSTNode *bt=NULL;
- int i=0;
- while (i<n)
- InsertBST(bt,A[i++]);
- return bt;
- }
-
- void DispBST(BSTNode *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(")");
- }
- }
- }
-
-
-
-
- KeyType predt=-32767;
- int JudgeBST(BSTNode *bt)
- {
- int b1,b2;
- if (bt==NULL)
- return 1;
- else
- {
- b1=JudgeBST(bt->lchild);
- 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("\n");
- printf("bt%s\n",(JudgeBST(bt)?"是一棵BST":"不是一棵BST"));
- bt->lchild->rchild->key = 30;
- printf("修改后的二叉树:");
- DispBST(bt);
- printf("\n");
- printf("bt%s\n",(JudgeBST(bt)?"是一棵BST":"不是一棵BST"));
- return 0;
- }
运行结果:知识点总结:
判断是否是二叉排序树。
0 0