#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
typedef struct TreeNode* BT;
typedef struct TreeNode* BinTree;
struct TreeNode
{
int data;
BinTree Left;
BinTree Right;
};
TreeNode* find(int elem, BinTree BT)
{
if (BT == NULL)
return NULL;
if (elem > BT->data)
return find(elem, BT->Right);
else if (elem < BT->data)
return find(elem, BT->Left);
else
return BT;
}
TreeNode* find2(int elem, BinTree BT)
{
while (BT!=NULL)
{
if (elem > BT->data)
BT = BT->Right;
else if (elem < BT->data)
BT = BT->Left;
else
return BT;
}
return NULL;
}
BinTree insertNode(int elem, BinTree &BT)
{
if (BT == NULL)
{
BT = (BinTree)malloc(sizeof(TreeNode));
BT->data = elem;
BT->Left = NULL;
BT->Right = NULL;
}
else
{
if (elem < BT->data)
BT->Left = insertNode(elem, BT->Left);
else if (elem > BT->data)
BT->Right = insertNode(elem, BT->Right);
}
return BT;
}
TreeNode* findMax(BinTree BT)
{
if (BT->Right == NULL)
return BT;
else
return findMax(BT->Right);
}
TreeNode* findMin(BinTree BT)
{
if (BT->Left == NULL)
return BT;
else
return findMin(BT->Left);
}
BinTree deleteNode(int elem, BinTree BT)
{
TreeNode* temp;
if (BT == NULL)
printf("not found\n");
else if (elem < BT->data)
BT->Left = deleteNode(elem, BT->Left);
else if (elem > BT->data)
BT->Right = deleteNode(elem, BT->Right);
else
{
if (BT->Left && BT->Right)
{
temp = findMin(BT->Right);
BT->data = temp->data;
BT->Right = deleteNode(BT->data, BT->Right);
free(temp);
}
else
{
temp = BT;
if (BT->Left == NULL)
BT = BT->Right;
else if (BT->Right == NULL)
BT = BT->Left;
free(temp);
}
}
return BT;
}
int main()
{
BinTree BT;
BT = NULL;
insertNode(30, BT);
insertNode(37, BT);
insertNode(28, BT);
insertNode(39, BT);
if (find(28, BT) == NULL)
printf("null\n");
else
printf("%d\n", find(28, BT)->data);
BT = deleteNode(28, BT);
if (find(28, BT) == NULL)
printf("null\n");
else
printf("%d\n", find(28, BT)->data);
return 0;
}
|