tree.h
#ifndef TREE_H
#define TREE_H
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef struct
{
int key;
char value[20];
}DATA, *LPDATA;
typedef struct treenode
{
DATA data;
struct treenode *LChild;
struct treenode *RChild;
}NODE, *LPNODE;
typedef struct binarySearchTree
{
LPNODE root;
int treeSize;
}BST, *LPBST;
//传入数据
LPNODE createNode(DATA data);
LPBST createBST();
int size(LPBST tree);
int empty(LPBST tree);
void insertNode(LPBST tree, DATA data);
void printNode(LPNODE curNode);
void midOrder(LPNODE tree);
LPNODE searchBST(LPBST tree, int key);
void deleteNode(LPBST tree, int key);
#endif
tree.c
#include "tree.h"
//传入数据
LPNODE createNode(DATA data)
{
LPNODE newnode = (LPNODE)malloc(sizeof(NODE));
assert(newnode);
newnode->data = data;
newnode->LChild = NULL;
newnode->RChild = NULL;
return newnode;
}
LPBST createBST()
{
LPBST tree = (LPBST)malloc(sizeof(BST));
assert(tree);
tree->root = NULL;
tree->treeSize = 0;
return tree;
}
int size(LPBST tree)
{
return tree->treeSize;
}
int empty(LPBST tree)
{
return tree==NULL?0:tree->treeSize == 0;
}
void insertNode(LPBST tree, DATA data)
{
LPNODE newNode = createNode(data);
LPNODE pmove = tree->root;
LPNODE prepmove = NULL;
while (pmove != NULL)
{
prepmove = pmove;
if(pmove->data.key > data.key)
{
pmove = pmove->LChild;
}
else if(pmove->data.key < data.key)
{
pmove = pmove->RChild;
}
else
{
strncpy(pmove->data.value, data.value, 20);
return ;
}
}
if(tree->root == NULL)
{
tree->root = newNode;
}
else
{
if(prepmove->data.key > data.key)
{
prepmove->LChild = newNode;
}
else
{
prepmove->RChild = newNode;
}
}
tree->treeSize++;
}
void printNode(LPNODE curNode)
{
printf("%d:%s\n", curNode->data.key, curNode->data.value);
return ;
}
//遍历树
void midOrder(LPNODE tree)
{
if(tree != NULL)
{
midOrder(tree->LChild);
printNode(tree);
midOrder(tree->RChild);
}
return ;
}
test.c
#include "tree.h"
int main()
{
int i;
LPBST tree = createBST(); //创建二叉搜索树
DATA data[8] = { 10,"张三",5,"李四",49,"王五",2,"小芳",
18,"小黑",89,"小红",0,"小明",22,"小花" };
for (i = 0; i < 8; i++)
{
insertNode(tree, data[i]); //插入数据
}
midOrder(tree->root);
return 0;
}
Makefile
tree:tree.c test.c
gcc -o tree tree.c test.c
clean:
rm *.o