數據結構實驗之查找二:平衡二叉樹 SDUT 3374

Problem Description
根據給定的輸入序列建立一棵平衡二叉樹,求出建立的平衡二叉樹的樹根。

Input
輸入一組測試數據。數據的第1行給出一個正整數N(n <= 20),N表示輸入序列的元素個數;第2行給出N個正整數,按數據給定順序建立平衡二叉樹。

Output
輸出平衡二叉樹的樹根。

Sample Input
5
88 70 61 96 120
Sample Output
70

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
    int data;
    int deep;
    struct node *left, *right;
};

int max(int x, int y)
{
    if(x>y) return x;
    else return y;
}

int deep(struct node *root)
{
    if(root==NULL) return 0;
    else return root->deep;
}

struct node *ll(struct node *root)
{
    struct node *p, *q;
    p = root;
    q = root->left;
    p->left = q->right;
    q->right = p;
    p->deep = max(deep(p->left), deep(p->right))+1;
    q->deep = max(deep(q->left), deep(q->right))+1;
    return q;
};

struct node *rr(struct node *root)
{
    struct node *p, *q;
    p = root;
    q = root->right;
    p->right = q->left;
    q->left = p;
    p->deep = max(deep(p->right), deep(p->left))+1;
    q->deep = max(deep(q->right), deep(q->left))+1;
    return q;
};

struct node *rl(struct node *root)
{
    root->right = ll(root->right);
    root = rr(root);
    return root;
}

struct node *lr(struct node *root)
{
    root->left = rr(root->left);
    root = ll(root);
    return root;
}

struct node *add(struct node *root, int x)
{
    if(root==NULL)
    {
        root = (struct node *)malloc(sizeof(struct node));
        root->left = NULL;
        root->right = NULL;
        root->data = x;
        root->deep = 1;
    }
    else
    {
        if(x<root->data)
        {
            root->left = add(root->left, x);
            if(deep(root->left)-deep(root->right) > 1)
            {
                if(x < root->left->data) root = ll(root);
                else root = lr(root);
            }
        }
        else
        {
            root->right = add(root->right, x);
            if(deep(root->right)-deep(root->left) > 1)
            {
                if(x < root->right->data) root = rl(root);
                else root = rr(root);
            }
        }
        root->deep = max(deep(root->left), deep(root->right)) + 1;
    }
    return root;
}

int main()
{
    int n, i, x;
    struct node *root;
    scanf("%d", &n);
    root = NULL;
    for(i=0;i<n;i++)
    {
        scanf("%d", &x);
        root = add(root, x);
    }
    printf("%d\n", root->data);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章