I think it is necessary to understand the following code and understand recursive operation!
[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 */
TmpCell = FindMin (T-> Right );
T-> Element = TmpCell-> Element;
T-> Right = DeleteTree (T-> Element, T-> Right );
}
Else
{
TmpCell = T;
If (T-> Left = NULL)
T = T-> Right;
Else if (T-> Left = NULL)
T = T-> Left;
Free (TmpCell );
}
}
}
Return T;
}
// Traverse in the middle order. Print.
Void ShowTree (SearchTree T)
{
If (T! = NULL)
{
ShowTree (T-> Left );
Printf ("% d", T-> Element );
ShowTree (T-> Right );
}
}
Int main (void)
{
Position tree = NULL;
Tree = Insert (6, tree );
Tree = Insert (2, tree );
Tree = Insert (8, tree );
Tree = Insert (1, tree );
Tree = Insert (5, tree );
Tree = Insert (4, tree );
Tree = Insert (3, tree );
DeleteTree (3, tree );
// DeleteTree (3, tree );
// DeleteTree (6, tree );
ShowTree (tree );
Printf ("\ n ");
FindMax (tree );
FindMin (tree );
Return 0;
}
From angelbosj's column