|Codeup|| bfs遍历树找值hash|dfs|算法9-9~9-12:平衡二叉树的基本操作

link
算法9-9~9-12:平衡二叉树的基本操作

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

输入

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

样例输入

8 3
1 3 5 7 8 9 10 15
9 2 5

输出

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

样例输出

1 0 1

提示

在本题中,
首先需要按照题目描述中的算法完成平衡二叉树的构造过程,之后需要通过在平衡二叉树中的不断向下查找,
将需要查询的值与当前节点的值进行比较,
直到确定被查询的值是否存在。

通过课本中的性能分析部分,
不难发现平衡二叉树的查找、插入、删除等
操作的时间复杂度均为O(log2n),
这是通过利用旋转操作使二叉树保持平衡状态而保证的。


//bfs
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
int n,m;
vector<int>inquire;

struct node{
   
    int v,h;
    node* lchild,*rchild;
};

int getHeight(node* root){
   
    if(root==NULL)return 0;
    else 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 L(node* &root){
   
    node* tmp=root->rchild;
    root->rchild=tmp->lchild;
    tmp->lchild=root;
    updateHeight(root);
    updateHeight(tmp);
    root=tmp;
}

void R(node* &root){
   
    node* tmp=root->lchild;
    root->lchild=tmp->rchild;
    tmp->rchild=root;
    updateHeight(root);
    updateHeight(tmp);
    root=tmp;
}
void insert(node* &root,int v){
   
    if(root==NULL){
   
        root=new node;
        root->v=v;
        root->h=1;
        root->lchild=root->rchild=NULL;
        return;
    }
    if(v<root->v){
   
        insert(root->lchild,v);
        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);
        if(getBalanceFactor(root)==-2){
   
            if(getBalanceFactor(root->rchild)==-
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值