二叉查找树

// 二叉查找树BST
// 查找
void search(node* root, int x) {
	if(root == NULL) {
		printf("空树");
		return;
	}
	if(x == root->data) {
		printf("%d\n",root->data);
	} else if(x < root->data) {
		search(root->l, x);
	} else {
		search(root->r, x);
	}
}  //O(h) h为树的高度
// 插入
void insert(node* &root, int x) { //引用
	if(root == NULL) {
		root = newNode(x);
		return;
	}
	if(x == root->data) {
		printf("已存在");
		return;
	} else if(x < root->l) {
		insert(root->l, x);
	} else {
		insert(root->r, x);
	}
}  //O(h)
// 建BST
node* create(int data[], int n) {
	node* root = NULL;
	for(int i=0; i<data; i++) {
		insert(root, data[i]);
	}
	return root;
}
// BST的删除
// 寻找以root为根节点的树中的最大权值节点
node* findMax(node* root) {
	while(root->r != NULL) {
		root = root->r;
	}
	return root;
}
// 寻找以root为根节点的树中的最大权值节点
node* findMin(node* root) {
	while(root->l != NULL) {
		root = root->l;
	}
	return root;
}
// 删除以root为根节点的树中权值为x的节点
void deleteNode(node* &node, int x) { //引用
	if(root == NULL) return;
	if(root->data == x) {
		if(root->l == NULL && root->r == NULL) { //没有孩子
			root = NULL;
		} else if (root->l != NULL) { //有左孩子(即:当只有左孩子或二孩子都有时都处理左孩子)
			node* temp = findMax(root->l);  //左子树里找最大的提上去
			root->data = temp->data;
			deleteNode(root->l, temp->data);
		} else { //只有右孩子(处理右孩子)
			node* temp = findMin(root->r);  //右子树里找最小的提上去
			root->data = temp->data;
			deleteNode(root->r, temp->data);
		}
	} else if(root->data > x) {
		deleteNode(root->l, x);
	} else {
		deleteNode(root->r, x);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值