【数据结构】NOJ025 二叉排序树的插入和删除(严9.35、9.36和9.37)

1. 题目

在这里插入图片描述

示例输入
12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1
10 17
6
12
示例输出
12 13 16
4 6 8 10 12 13 16 18
4 8 10 13 16 18

2. 代码

#include <iostream>

using namespace std;

typedef struct tree{
	int data;
	struct tree *lc, *rc;
}Tree;

Tree* CreateTree(){
	int tmp;
	cin >> tmp;
	if(tmp == -1) return NULL;
	Tree *t = (Tree*)malloc(sizeof(Tree));
	t->data = tmp;
	t->lc = CreateTree();
	t->rc = CreateTree();
	return t;
}

void Search(Tree *t, int a, int b){
	if(t){
		if(t->data >= b){
			Search(t->lc, a, b);
		}
		else if(t->data <= a){
			Search(t->lc, a, b);
		}
		else{
			Search(t->lc, a, b);
			cout << t->data << " ";
			Search(t->rc, a, b);
		}
	}
}

Tree* Insert(Tree *t, int x){
	if(!t){
		t = (Tree*)malloc(sizeof(Tree));
		t->data = x;
		t->lc = NULL;
		t->rc = NULL;
		return t;
	}
	if(t->data == x) return t;
	if(t->data > x){
		t->lc = Insert(t->lc, x);
		return t;
	}
	if(t->data < x){
		t->rc = Insert(t->rc, x);
		return t;
	}
}

void InOrdOutput(Tree *t){
	if(t){
		InOrdOutput(t->lc);
		cout << t->data << " ";
		InOrdOutput(t->rc); 
	}
}

void Remove(Tree* &t){
	if(!t->lc && !t->rc){
		t = NULL;
	}
	else if(!t->lc){
		t = t->rc;
	}
	else if(!t->rc){
		t = t->lc;
	}
	else{
		Tree *p = t->lc;
		while(p->rc){
			p = p->rc;
		}
		p->rc = t->rc;
		t = t->lc;
	}
}

void Delete(Tree* &t, int x){
	if(t->data == x){
		Remove(t);
	}
	else if(t->data > x){
		Delete(t->lc, x);
	}
	else{
		Delete(t->rc, x);
	}
}

int main(){
	Tree *t = CreateTree();
	int a, b, x, y;
	cin >> a >> b >> x >> y;
	Search(t, a, b);
	cout << endl;
	t = Insert(t, x);
	InOrdOutput(t);
	cout << endl;
	Delete(t, x);
	Delete(t, y);
	InOrdOutput(t);
	cout << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值