二叉树的创建、打印、删除等函数(c)
我认为要看懂下面的代码,对于递归的运行,要很了解才是!
[html]
#include <stdio.h>
#include <stdlib.h>
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
/* Placein the implement file */
struct TreeNode
{
int Element;
SearchTree Left;
SearchTree Right;
};
/* clean up tree */
SearchTree MakeEmpty(SearchTree T)
{
if (T != NULL)
{
MakeEmpty(T->Left);
MakeEmpty(T->Right);
free(T);
T = NULL;
}
return NULL;
}
/* find x in the tree */
Position Find(int X, SearchTree T)
{
if (T != NULL)
{
if (T->Element == X)
{
return T;
}
else if(T->Element < X)
{
return Find(X, T->Right);
}
else if (T->Element > X)
{
return Find(X, T->Left);
}
}
else
{
return NULL;
}
}
/* find min */
Position FindMin(SearchTree T)
{
if (T == NULL)
{
return NULL;
}
else
{
if (T->Left != NULL)
{
FindMin(T->Left);
}
else
{
printf("MIN = %d\n", T->Element);
return T;
}
}
}
/* find max */
Position FindMax(SearchTree T)
{
if (T == NULL)
{
return NULL;
}
else
{
if (T->Right!= NULL)
{
FindMax(T->Right);
}
else
{
printf("MAX = %d\n", T->Element);
return T;
}
}
}
/* insert x */
SearchTree Insert(int X, SearchTree T)
{
if (T == NULL)
{
T = (SearchTree)malloc(sizeof(struct TreeNode));
if (T == NULL)
{
printf("out of space!!!\n");
}
else
{
T->Element = X;
T->Left = NULL;
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;
}
/* delete x */
SearchTree DeleteTree(int X, SearchTree T)
{
Position TmpCell;
if (T == NULL)
{
printf("X not found.\n");
}
else
{
if (X < T->Element) /* go to left */
{
T->Left = DeleteTree(X, T->Left);
}
else if (X > T->Element)
{
T->Right = DeleteTree(X, T->Right);
}
else
{
if (T->Left && T->Right) /* Two children */
{
/* replace with smallest in right subtree */
 
补充:软件开发 , C语言 ,