#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
typedef int dataType;
typedef struct node * BSTptr;
struct node
{
dataType data;
BSTptr lchild;
BSTptr rchild;
};
BSTptr parent1;
BSTptr parent2;
void addNodeToBST(BSTptr *root, dataType key)
{
BSTptr ptr;
if(NULL == *root)
{
ptr = (BSTptr)malloc(sizeof(struct node));
assert(ptr);
ptr->data = key;
ptr->lchild = ptr->rchild = NULL;
(*root) = ptr;
}
else if((*root)->data > key)
{
addNodeToBST(&((*root)->lchild), key);
}
else if((*root)->data < key)
{
addNodeToBST(&((*root)->rchild), key);
}
else
{
printf("the key exists");
return;
}
}
void preorder(const BSTptr root)
{
if(NULL != root)
{
printf("%d\n", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
void inorder(const BSTptr root)
{
if(NULL != root)
{
inorder(root->lchild);
printf("%d\n", root->data);
inorder(root->rchild);
}
}
void postorder(const BSTptr root)
{
if(NULL != root)
{
postorder(root->lchild);
postorder(root->rchild);
printf("%d\n", root->data);
}
}
BSTptr maxNode(BSTptr tree)
{
while(tree->rchild)
{
parent1 = tree;
tree = tree->rchild;
}
return tree;
}
BSTptr minNode(BSTptr tree)
{
while(tree->lchild)
{
parent1 = tree;
tree = tree->lchild;
}
return tree;
}
BSTptr search(BSTptr tree, dataType key)
{
while(tree)
{
if(tree->data == key)
{
return tree;
}
else if(tree->data > key)
{
tree = tree->lchild;
}
else
{
tree = tree->rchild;
}
}
return NULL;
}
void deleteNode(BSTptr *tree, dataType key)
{
BSTptr node;
node = search(*tree, key);
if(NULL == node)
{
printf("there is no key in the tree!\n");
exit(1);
}
if(!(node->lchild) && !(node->rchild))
{
free(node);
node = NULL;
}
else if(node->lchild && !(node->rchild))
{
node->data = node->lchild->data;
free(node->lchild);
node->lchild = NULL;
}
else if(node->rchild && !(node->lchild))
{
node->data = node->rchild->data;
free(node->rchild);
node->rchild = NULL;
}
else
{
BSTptr tmp = NULL;
tmp = maxNode(node->lchild);
node->data = tmp->data;
if(!(tmp->lchild) && !(tmp->rchild))
{
free(tmp);
tmp = NULL;
}
else if(tmp->lchild && !(tmp->rchild))
{
tmp->data = tmp->lchild->data;
free(tmp->lchild);
tmp->lchild = NULL;
}
else if(tmp->rchild && !(tmp->lchild))
{
tmp->data = tmp->rchild->data;
free(tmp->rchild);
tmp->rchild = NULL;
}
}
}
int main(void)
{
BSTptr tree = NULL;
BSTptr node;
addNodeToBST(&tree, 10);
addNodeToBST(&tree, 6);
addNodeToBST(&tree, 4);
addNodeToBST(&tree, 8);
addNodeToBST(&tree, 14);
addNodeToBST(&tree, 12);
addNodeToBST(&tree, 16);
preorder(tree);
printf("\n");
inorder(tree);
printf("\n");
postorder(tree);
printf("\n");
deleteNode(&tree, 14);
preorder(tree);
printf("\n");
inorder(tree);
printf("\n");
postorder(tree);
//node = search(tree, 8);
//printf("\n%d\n", node->data);
return 0;
}
复习数据结构之二叉查找树
最新推荐文章于 2024-06-06 23:56:32 发布