二叉搜索树常用的一些操作,如插入,删除,寻找最大最小节点,前序中序后序遍历等
typedef int itemType;
typedef struct BinNode{
itemType data;
struct BinNode *left;
struct BinNode *right;
BinNode(itemType d, struct BinNode *l, struct BinNode *r)
{data = d;left = l;right = r;}
}Node, *pNode, *Tree;
//插入节点
void insert(Tree &t, const itemType &x)
{
if(t == NULL){
t = new BinNode(x, NULL, NULL);
}
else if(x < t->data)
insert(t->left, x);
else if(x > t->data)
insert(t->right, x);
}
//寻找最小值
pNode findMin(Tree t)
{
if(t != NULL)
while(t->left != NULL)
t = t->left;
return t;
}
//寻找最大值
pNode findMax(Tree t)
{
if(t != NULL)
while(t->right != NULL)
t = t->right;
return t;
}
//删除节点
void remove(Tree &t, const itemType &x)
{
if(t == NULL)
return;
if(x < t->data)
remove(t->left, x);
else if(x > t->data)
remove(t->right, x);
else if(t->left != NULL && t->right != NULL){
t->data = findMin(t->right)->data;
remove(t->right, t->data);
}else{
pNode oldNode = t;
t = (t->left != NULL) ? t->left : t->right;
delete oldNode;
}
}
//输出
void visit(Tree t, int depth)
{
while(depth--)
cout<<"--";
cout<<t->data<<endl;
}
//前序遍历
void preOrder(Tree t, int depth, void (*visit)(Tree, int))
{
if(t != NULL){
(*visit)(t, depth);
preOrder(t->left, depth+1, visit);
preOrder(t->right, depth+1, visit);
}
}
//中序遍历
void inOrder(Tree t, int depth, void (*visit)(Tree,int))
{
if(t != NULL){
inOrder(t->left, depth+1, visit);
(*visit)(t, depth);
inOrder(t->right, depth+1, visit);
}
}
//后序遍历
void postOrder(Tree t, int depth, void (*visit)(Tree, int))
{
if(t != NULL){
postOrder(t->left, depth+1, visit);
postOrder(t->right, depth+1, visit);
(*visit)(t, depth);
}
}
//删除整个树
void makeEmpty(Tree &t)
{
if(t != NULL){
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t = NULL;
}
//寻找某一节点
pNode search(Tree t, const itemType &x)
{
if(t == NULL)
return NULL;
if(t->data == x)
return t;
else if(x < t->data)
return search(t->left, x);
else
return search(t->right, x);
}