#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
struct BTNode
{
int data;
BTNode* left;
BTNode* right;
};
BTNode* FindMin(BTNode* pRoot);
BTNode* BSTSearch(BTNode* bt, int key)//查找
{
if (bt == NULL)
return NULL;
else
{
if (bt->data == key)
return bt;
else if (bt->data < key)
return BSTSearch(bt->right, key);
else
return BSTSearch(bt->left, key);
}
}
int BSTInsert(BTNode* &bt, int key)//插入操作
{
if (bt == NULL)
{
bt = new BTNode();
bt->left = bt->right = NULL;
bt->data = key;
return 1;
}
else {
if (bt->data == key)
return 0;
else if (key < bt->data)
return BSTInsert(bt->left, key);
else
return BSTInsert(bt->right, key);
}
}
void CreateBST(BTNode* &bt, int key[], int n)//创建二叉排序树
{
int i;
bt = NULL;
for (i = 0; i < n; ++i)
BSTInsert(bt, key[i]);
}
void Inoeder(BTNode* pRoot)//中序遍历
{
if (pRoot == NULL)
return;
Inoeder(pRoot->left);
printf("%d ", pRoot->data);
Inoeder(pRoot->right);
}
void Delete(BTNode* &pNode)//删除节点pNode
{
BTNode*q = NULL, *s=NULL;
if (pNode->right == NULL)
{
q = pNode;
pNode = pNode->left;
free(q);
}
else if(pNode->left==NULL)
{
q = pNode;
pNode = pNode->right;
free(q);
}
else
{
q = pNode;
s = pNode->left;
while (s->right)
{
q = s;
s = s->right;
}
pNode->data = s->data;
if (q != pNode)
q->right = s->left;
else
q->left = s->left;
free(s);
}
}
int DeleteNode(BTNode* &pRoot, int key)//删除关键字key的节点
{
if (pRoot == NULL)
return 0;
else
{
if (key == pRoot->data)
Delete(pRoot);
else if (key < pRoot->data)
DeleteNode(pRoot->left, key);
else
DeleteNode(pRoot->right, key);
}
}
BTNode* FindMin(BTNode* pRoot)
{
if (pRoot == NULL)
return NULL;
while (pRoot->left)
{
pRoot = pRoot->left;
}
return pRoot;
}
BTNode* FindMax(BTNode* pRoot)
{
if (pRoot == NULL)
return NULL;
while (pRoot->right)
{
pRoot = pRoot->right;
}
return pRoot;
}
int main()
{
int data[10] = { 62,88,58,47,35,73,51,99,37,93 };
BTNode* pRoot = NULL;
CreateBST(pRoot, data, 10);
Inoeder(pRoot);
printf("\n");
//Delete(pRoot, 51);
DeleteNode(pRoot, 35);
Inoeder(pRoot);
cout << endl;
//cout << FindMax(pRoot)->data << endl;
}