二叉排序树一些操作

输入若干个不同的正整数(以0结束),按顺序建立一颗二叉排序树,输出中序遍历结果。再输入一个数X,在建好的二叉排序树中查找有无关键字X这个结点,有则删除该节点,无则插入这个结点,删除或插入后还要保证满足二叉排序树的要求。最后请用邻接表的形式再次输入该二叉排序树。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
struct node {
	node* left;
	node*right;
	int val;
};
node*root;
void build(int k, struct node*&x)
{
	if (x == NULL)
	{
		x = new struct node;
		x->left = NULL;
		x->right = NULL;
		x->val = k;
	}
	else
	{
		if (k < x->val)
		{
			build(k, x->left);
		}
		else
		{
			build(k, x->right);
		}
	}
}
void puts(struct node *x)
{
	if (x != NULL)
	{
		puts(x->left);
		cout << x->val ;
		puts(x->right);
	}
}
void exers(node *&x)
{
	if (x->left == NULL && x->right == NULL)
	{
		node *n = root;
		if (n->val == x->val)
			root = NULL;
		while (1)
		{
			if (n->left!=NULL&&n->left->val == x->val)
			{
				n->left = NULL;
				break;
			}
			if (n->right!=NULL&&n->right->val == x->val)
			{
				n->right = NULL;
				break;
			}
			if (x->val > n->val)
			{
				n = n->right;
			}
			else
			{
				n = n->left;
			}
		}
	}
	else
	{
		if (x->left != NULL && x->right != NULL)
		{
			node*n = x->left;
			while (1)
			{
				if (n->right == NULL)
				{
					n->right = x->right;
					break;
				}
				n = n->right;
			}
			x->right = x->left->right;
			x->val = x->left->val;
			x->left = x->left->left;	
		}
		else
		{
			if (x->left != NULL)
			{
				x->right = x->left->right;
				x->val = x->left->val;
				x->left = x->left->left;
			}
			else
			{
				x->left = x->right->left;	
				x->val = x->right->val;				
				x->right = x->right->right;
			}
		}
	}
}
void finds(int x)
{
	node*n = root;
	while (1)
	{
		if (n->val == x)
		{
			cout << "YES" << endl;
			exers(n);
			return;
		}
		if (x > n->val)
			n = n->right;
		else
			n = n->left;
	}
}
void print(node *x)
{
	if (x == NULL)
		return;
	cout << x->val;
	if (x->left || x->right)cout << "(";
	if (x->left)print(x->left);
	if (x->right)cout << ",";
	if (x->right)print(x->right);
	if (x->left || x->right)cout << ")";
}
int main()
{
	int k;
	int X;
	while (1)
	{
		cin >> k;
		if (k == 0)
			break;
		build(k, root);
	}
	puts(root);
	cout << endl;
	cin >> X;
	finds(X);
	puts(root);
	cout << endl;
	print(root);
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值