二叉排序树BST+求树深度算法

时间:2021-09-28 16:06:49
#include "stdio.h"
#include "malloc.h"
typedef struct node
{
int key;
struct node *lchild, *rchild; }BSTNode, *BSTree; void InsertBST(BSTree *bst, int key)
{
BSTree s;
if (*bst == NULL)
{
s = (BSTree)malloc(sizeof(BSTNode));
s->key = key;
s->lchild = NULL;
s->rchild = NULL;
*bst = s;
}
else if (key<(*bst)->key) InsertBST(&((*bst)->lchild), key);
else if (key > (*bst)->key) InsertBST(&((*bst)->rchild), key);
} void CreateBST(BSTree *bst)
{
int key;
*bst = NULL;
scanf("%d",&key);
while (key != 0)
{
InsertBST(bst, key);
scanf("%d",&key);
}
} void inorder(BSTree bt)
{
if (bt != NULL)
{
inorder(bt->lchild);
printf("%3d",bt->key);
inorder(bt->rchild);
}
} int FindTreeDeep(BSTree BT){
int deep=0;
if(BT){
int lchilddeep=FindTreeDeep(BT->lchild);
int rchilddeep=FindTreeDeep(BT->rchild);
deep=lchilddeep>=rchilddeep?lchilddeep+1:rchilddeep+1;
}
return deep;
} int main()
{
BSTree bt;
CreateBST(&bt);
inorder(bt);
printf("\n");
printf("%d\n",FindTreeDeep(bt));
getchar();
return 0;
}