Search 2 of 3374 data structure experiment: balanced binary tree

Search 2 of 3374 data structure experiment: balanced binary tree

Time Limit: 400MS Memory Limit: 65536KB

Problem Description

According to the given input sequence, a balanced binary tree is established, and the tree root of the balanced binary tree is obtained.

Input

Enter a set of test data. The first row of the data gives a positive integer N (N < = 20), N represents the number of elements of the input sequence; the second row gives N positive integers, and establishes a balanced binary tree according to the given order of the data.

Output

Outputs the root of a balanced binary tree.

Example Input

5
88 70 61 96 120

Example Output

70
#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    int height;
    node *left;
    node *right;
};
int height(node *root)
{
    if(root==NULL)return 0;
    return root->height;
}
node* LL(node *root)
{
    node* temp;
    temp=root->left;
    root->left=temp->right;
    temp->right=root;
    root->height=max(height(root->left),height(root->right))+1;
    temp->height=max(height(temp->left),height(temp->right))+1;
    return temp;
}
node* RR(node *root)
{
    node*temp;
    temp=root->right;
    root->right=temp->left;
    temp->left=root;
    root->height=max(height(root->left),height(root->right))+1;
    temp->height=max(height(temp->left),height(temp->right))+1;
    return temp;
}
node* LR(node *root)
{
    root->left=LL(root->left);
    return LL(root);
}
node* RL(node *root)
{
    root->right=RR(root->right);
    return RR(root);
}
node* creat(node *root,int data)
{
    if(root==NULL)
    {
        root=new node;
        root->data=data;
        root->left=root->right=NULL;
        root->height=1;
    }
    else if(data>root->data)
    {
        root->right=creat(root->right,data);
        if(height(root->right)-height(root->left)==2)
        {
            if(data>root->right->data)root=RR(root);
            else  root=RL(root);
        }
    }
    else if(data<root->data)
    {
        root->left=creat(root->left,data);
        if(height(root->left)-height(root->right)==2)
        {
            if(data>root->left->data)root=LR(root);
            else  root=LL(root);
        }
    }
    root->height=max(height(root->left),height(root->right))+1;
    return root;
}
int main()
{
    node *root=NULL;
    int num;
    cin>>num;
    for(int i=0;i<num;i++)
    {
        int data;
        cin>>data;
        root=creat(root,data);
    }
    printf("%d\n",root->data);
}

Posted on Mon, 04 May 2020 08:49:37 -0700 by dbakker