二叉搜索树常用操作函数

二叉搜索树常用的一些操作,如插入,删除,寻找最大最小节点,前序中序后序遍历等


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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值