pat甲级1066题(没写出来,本来代码还可以通过一部分的,现在一个也过不了了)

下次有时间了再去找里面的bug吧

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;

struct node
{
    int data;
    node *left,*right;
    int height;
};
node* newNode(int x)
{
    node *root =new node;
    root->data=x;
    root->height=1;
    root->left=root->right=NULL;
    return root;
}
int getHeight(node *root)
{
    if(root==NULL)
    {
        return 0;
    }
    return root->height;
}
int getBalancefactor(node* root)
{
    return getHeight(root->left)-getHeight(root->right);
}
void updateHeight(node* root)//
{

    root->height=max(getHeight(root->left),getHeight(root->right))+1;
}
void L(node* &root)//纠正点1
{
    node* temp=root->right;


    root->right=temp->left;
    temp->left=root;
    updateHeight(root);
    updateHeight(temp);
    root=temp;

}
void R(node* &root)
{
    node* temp=root->left;

    root->left=temp->right;
    temp->right=root;
    updateHeight(root);
    updateHeight(temp);
    root=temp;

}

void insert(node* &root,int x)
{

    if(root==NULL)
    {
        root=newNode(x);
        return;
    }
    else
    {
        //printf("1");
        if(x<root->data)
        {
            insert(root->left,x);
            updateHeight(root);
            if(getBalancefactor(root)==2)
            {
                if(getBalancefactor(root->left)==1)
                {
                    R(root);
                }
                else if(getBalancefactor(root->right)==-1)
                {
                    L(root->right);
                    R(root);
                }

            }


        }
        else
        {
            insert(root->right,x);
            updateHeight(root);

            if(getBalancefactor(root)==-2)
            {
                if(getBalancefactor(root->left)==-1)
                {
                    L(root);
                }
                else if(getBalancefactor(root->right)==1)
                {
                    R(root->right);
                    L(root);
                }

            }

        }

    }

}

int main()
{
    int num;
    scanf("%d",&num);
    node* root=NULL;//这里是出bug的地方,我写的是node* root =new node;
    for(int i=0; i<num; i++)
    {
        int x;

        scanf("%d",&x);
        insert(root,x);

    }

    printf("%d\n",root->data);

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值