1773 Problem A:平衡二叉树的基本操作

在本题中,读入一串整数,首先利用这些整数构造一棵平衡二叉树。另外给定多次查询,利用构造出的平衡二叉树,判断每一次查询是否成功。

输入

输入的第一行包含2个正整数n和k,分别表示共有n个整数和k次查询。其中n不超过500,k同样不超过500。
第二行包含n个用空格隔开的正整数,表示n个整数。
第三行包含k个用空格隔开的正整数,表示k次查询的目标。

输出

只有1行,包含k个整数,分别表示每一次的查询结果。如果在查询中找到了对应的整数,则输出1,否则输出0。
请在每个整数后输出一个空格,并请注意行尾输出换行。

样例输入

1 3 5 7 8 9 10 15
9 2 5

样例输出

1 0 1 
#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

struct node
{
	int v, h;
	node* lchild;
	node* rchild;
	node(int v) :v(v) { h = 1; lchild = rchild = NULL; }
};

int getHeight(node *root)
{
	if (root == NULL)
	{
		return 0;
	}
	return root->h;
}
void updateHeight(node* root)
{
	root->h=max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}

int  getBalanceFactor(node* root)
{
	return getHeight(root->lchild) - getHeight(root->rchild);
}

void R(node* &root)
{
	node* temp = root->lchild;
	root->lchild = temp->rchild;
	temp->rchild = root;
	updateHeight(root);
	updateHeight(temp);
	root = temp;
}
void L(node* &root)
{
	node* temp = root->rchild;
	root->rchild = temp->lchild;
	temp->lchild = root;
	updateHeight(root);
	updateHeight(temp);
	root = temp;
}
void insert(node* &root, int v)
{
	if (root == NULL)
	{
		root = new node(v);
		return;
	}
	if (v < root->v)
	{
		insert(root->lchild,v);
		updateHeight(root->lchild);
		updateHeight(root);
		if (getBalanceFactor(root) == 2)
		{
			if (getBalanceFactor(root->lchild) == 1)
			{
				R(root);
			}
			else if(getBalanceFactor(root->lchild) == -1)
			{
				L(root->lchild);
				R(root);
			}
		}
	}
	else
	{
		insert(root->rchild, v);
		updateHeight(root->rchild);
		updateHeight(root);
		if (getBalanceFactor(root) == -2)
		{
			if (getBalanceFactor(root->rchild) == -1)
			{
				L(root);
			}
			else if (getBalanceFactor(root->rchild) == 1)
			{
				R(root->rchild);
				L(root);
			}
		}
	}
}
int search(node* root,int v)
{
    if(root==NULL)
    {
        return 0;
    }
    if(v==root->v)
    {
        return 1;
    }
    else if(v<root->v)
    {
        return search(root->lchild,v);
    }
    else
    {
        return search(root->rchild,v);
    }
}
int main()
{
	int n,k;
	cin>>n>>k;
	node* root=NULL;
	for(int i=0;i<n;i++)
	{
	    int v;
	    cin>>v;
	    insert(root,v);
	}
	for(int i=0;i<k;i++)
	{
	    int v;
	    cin>>v;
	    if(i<k-1)
	    {
	        cout<<search(root,v)<<" ";
	    }
	    else
	    {
	        cout<<search(root,v)<<endl;
	    }
	    
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值