/*************************************************
*
* file name:BianrySearchTree.c
* author :[email protected]
* date :2024/05/04
* brief :二叉查找树的接口设计
* note :None
*
* CopyRight (c) 2024 [email protected] All Right Reseverd
*
**************************************************/
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include "drawtree.h"
/*************************************************
*
* func name :
* brief :
* func parameter:
*
*
* return :None
* note :None
* func author :[email protected]
* date :2024/05/04
* version :V1.0
**************************************************/
// 二叉查找树的节点的结构体构建
#if 0
typedef int DataType_t;
typedef struct BSTreeNode
{
DataType_t KeyVal;
struct BSTreeNode *lchild;
struct BSTreeNode *rchild;
} BSTree_t;
#endif
// 创建BST树的根节点,并对根节点初始化
BSTree_t *BSTree_Create(DataType_t keyval)
{
// 创建一个根节点并为根节点申请内存
BSTree_t *Root = (BSTree_t *)calloc(1, sizeof(BSTree_t)) if (Root == NULL)
{
perror("calloc memory for root is failed!\n");
exit(-1);
}
// 初始化根节点
Root->KeyVal = keyval;
Root->lchild = NULL;
Root->rchild = NULL;
return Root;
}
// 创建一个BST树的新节点,并对新结点进行初始化
BSTree_t *BSTree_NewNode(DataType_t keyval)
{
// 创建一个新结点,并为新结点申请新内存
BSTree_t *New = (BSTree_t *)calloc(1, sizeof(BSTnode_t));
if (New == NULL)
{
perror("calloc memory for newnode is failed!\n");
exit(-1);
}
// 初始化根节点
New->KeyVal = keyval;
New->lchild = NULL;
New->rchild = NULL;
return New;
}
// 向BST树中加入节点
bool BSTree_InsertNode(BSTree_t *Root, DataType_t keyval)
{
BSTree_t *New = BSTree_NewNode(keyval);
BSTree_t *Proot = Root;
if (New == NULL)
{
printf("Create NewNode Error\n");
return false;
}
// 判断根节点是否为空
if (Root == NULL)
{
Root = New;
return true;
}
else // 二叉查找树非空
{
while (Proot)
{
if (New->KeyVal == Proot->KeyVal) // 新节点键值是否与根节点相同,相同则插入失败
{
printf("Insert newnode failed!\n");
return false;
}
else // 如果不相等则继续分析
{
if (New->KeyVal < Proot->KeyVal) // 新结点的键值小于根节点的键值,则把根节点的左子树作为新的根节点
{
if (Proot->lchild == NULL) // 如果左节点为空就直接插入
{
Proot->lchild = New;
break;
}
Proot = Proot->lchild;
}
else // 新结点的键值大于根节点的键值,则把根节点的右子树作为新的根节点
{
if (Proot->rchild == NULL) // 如果右节点为空就直接插入
{
Proot->rchild = New;
break;
}
Proot = Proot->rchild;
}
}
}
}
return true;
}
int main(void)
{
BSTree_t *Root = BSTree_Create(10);
BSTree_InsertNode(Root, 2);
BSTree_InsertNode(Root, 8);
BSTree_InsertNode(Root, 14);
BSTree_InsertNode(Root, 23);
return 0;
}
标签:Proot,接口,二叉,查找,BSTree,New,NULL,Root,节点
From: https://www.cnblogs.com/bell-c/p/18172978