#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct treenode *ptrtonode;
struct treenode
{
int data;
ptrtonode left;
ptrtonode right;
};
ptrtonode buildtree(int num[], int n);
ptrtonode new_node(int n);
void treval(ptrtonode T);
ptrtonode insertt(ptrtonode T, int n);
ptrtonode find_min(ptrtonode T);
ptrtonode delete_tree(ptrtonode T, int n);
int main()
{
int num[10] = {5,12,14,6,3,7,9,8,4,23};
ptrtonode root = NULL;
/* while(cin >> n)
{
num[i] = n;
++i;
}*/
//建树
root = buildtree(num, 10);
treval(root);
cout << endl;
delete_tree(root, 7);
treval(root);
return 0;
}
ptrtonode buildtree(int num[], int n)
{
ptrtonode T;
T = new_node(num[0]);
for(int i=1; i<n; i++)
{
insertt(T, num[i]);
}
return T;
}
ptrtonode new_node(int n)
{
ptrtonode T;
T = (ptrtonode)malloc(sizeof(struct treenode));
T->data = n;
T->left = T->right = NULL;
return T;
}
ptrtonode insertt(ptrtonode T, int n)
{
if(T == NULL)
{
T = new_node(n);
}
else
{
if(n > T->data)
T->right = insertt(T->right, n);
if(n < T->data)
T->left = insertt(T->left, n);
}
return T;
}
ptrtonode delete_tree(ptrtonode T, int n)
{
ptrtonode tmpcell;
if(T == NULL )
{
cout <<"ERROR" <<endl;
return NULL;
}
else if(n < T->data)
{
T->left = delete_tree(T->left, n);
}
else if(n > T->data)
{
T->right = delete_tree(T->right, n);
}
else if(T->left && T->right) ///有左子树和右子树
{
tmpcell = find_min(T->right);
T->data = tmpcell->data;
T->right = delete_tree(T->right, T->data);
}
else //只有一棵子树或者没有子树
{
tmpcell = T;
if(T->left == NULL)
T = T->right;
else if(T->right == NULL) /***********这个 else 很重要!!!!******************/
T = T->left;
free(tmpcell);
}
return T;
}
ptrtonode find_min(ptrtonode T)
{
if(T == NULL)
return NULL;
if(T->left)
return find_min(T->left);
else
return T;
}
void treval(ptrtonode T)
{
if(T)
{
treval(T->left);
printf("%5d", T->data);
treval(T->right);
}
}
二叉搜索树的操作
最新推荐文章于 2023-11-13 18:40:26 发布