数据结构——二叉查找树
#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode
{
int data;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
typedef struct TreeNode* Position;
typedef struct TreeNode* SearchTree;
TreeNode* CreateNode(int X, TreeNode* left, TreeNode* right)
{
TreeNode* p;
p = (TreeNode*)malloc(sizeof(TreeNode));
if (p == NULL)
printf("分配内存空间失败!");
p->data = X;
p->left = left;
p->right = right;
return p;
}
TreeNode* Find(int X, SearchTree T)
{
if (T == NULL)
return NULL;
if (X < T->data)
return Find(X, T->left);
else if (X > T->data)
return Find(X, T->right);
else
return T;
}
TreeNode* FindMin(SearchTree T)
{
if (T == NULL)
return NULL;
else if (T->left == NULL)
return T;
else
return FindMin(T->left);
}
TreeNode* FindMax(SearchTree T)
{
if (T != NULL)
while (T->right != NULL)
T = T->right;
return T;
}
TreeNode* Insert(int X, SearchTree T)
{
if (T == NULL)
{
T = (TreeNode*)malloc(sizeof(TreeNode));
if (T == NULL)
printf("分配内存空间失败!");
else
{
T->data = X;
T->left = T->right = NULL;
}
}
else if (X < T->data)
T->left = Insert(X, T->left);
else if (X > T->data)
T->right = Insert(X, T->right);
else
printf("该节点已存在!");
return T;
}
TreeNode* Delete(int X, SearchTree T)
{
Position p;
if (T == NULL)
printf("未找到该元素!");
else if (X < T->data)
T->left = Delete(X, T->left);
else if (X > T->data)
T->right = Delete(X, T->right);
else if (T->left && T->right)
{
p = FindMin(T->right);
T->data = p->data;
T->right = Delete(T->data, T->right);
}
else
{
p = T;
if (T->left == NULL)
T = T->right;
else if (T->right == NULL)
T = T->left;
free(p);
}
return T;
}
void Display(SearchTree T,int X,int direction)
{
if (T != NULL)
{
if (direction == 0)
printf("%d是根节点\n", X);
else
{
if (direction == 1)
printf("%d是%d的%s儿子\n", T->data, X, "右");
else
printf("%d是%d的%s儿子\n", T->data, X, "左");
}
Display(T->left, T->data, -1);
Display(T->right, T->data, 1);
}
}
void main()
{
int i;
SearchTree T = NULL;
printf("依次添加:\n");
for (i = 0; i < 10; i++)
{
printf("%d", i);
T = Insert(i, T);
}
printf("\n");
printf("树的详细信息:\n");
Display(T, T->data, 0);
}