二叉排序樹實現(C語言)
阿新 • • 發佈:2019-02-19
#include <stdio.h>
#include <stdlib.h>
// 定義基本的資料結構和型別預定義
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
typedef int ElementType;
struct TreeNode
{
ElementType Element;
SearchTree Left;
SearchTree Right;
};
// 二叉樹遞迴插入元素
SearchTree Insert(ElementType X, SearchTree T )
{
if (T == NULL)
{
T = (SearchTree)malloc(sizeof(struct TreeNode));
if (T == NULL)
{
printf("tree malloc failed.\n");
return NULL;
}
T->Element = X;
T->Left = T->Right = NULL;
}
else if (X < T->Element)
{
T ->Left = Insert(X, T->Left);
}
else if (X > T->Element)
{
T->Right = Insert(X, T->Right);
}
return T;
}
// 遞迴的查詢某個元素
SearchTree Find(ElementType X, SearchTree T)
{
if (T == NULL)
{
return NULL;
}
else if (X < T->Element)
{
return Find(X, T->Left);
}
else if (X > T->Element)
{
return Find(X, T->Right);
}
else
{
return T;
}
}
// 遞迴的前序遍歷
ElementType PreOrder(SearchTree T)
{
if (T != NULL)
{
printf("%d\n", T->Element);
PreOrder(T->Left);
PreOrder(T->Right);
}
}
// 遞迴的查詢最小的元素所在的指標
SearchTree FindMin(SearchTree T)
{
if (T == NULL)
{
return NULL;
}
else if (T->Left == NULL)
{
return T;
}
else
{
return FindMin(T->Left);
}
}
// 遞迴的刪除某個元素
SearchTree Delete(ElementType X, SearchTree T)
{
Position TmpCell;
if (T == NULL)
{
printf("element not fount!\n");
}
else if (X < T->Element)
{
T->Left = Delete(X, T->Left);
}
else if (X > T->Element)
{
T->Right = Delete(X, T->Right);
}
else if (T->Left && T->Right)
{
// 處理待刪除節點有兩個子節點情況,採取將右子樹的最小節點代替刪除的節點,也可以使用
// 左子樹的最大節點代替刪除的元素
TmpCell = FindMin(T->Right);
T->Element = TmpCell->Element;
T->Right = Delete(T->Element, T->Right);
}
else
{
// 處理節點只有一個子節點或沒有子節點的情況
TmpCell = T;
if (T->Left == NULL)
T = T->Right;
else if (T->Right == NULL)
T = T->Left;
free(TmpCell);
}
return T;
}
int main()
{
//一定初始化T為NULL,否則後續插入判斷根節點是否為NULL會出錯
SearchTree T = NULL;
T = Insert(2, T);
T = Insert(1, T);
T = Insert(3, T);
PreOrder(T);
Delete(1, T);
PreOrder(T);
// Position tmp = FindMin(T);
// printf("%d\n", tmp->Element);
return 0;
}