平衡二叉树代码

先将平衡二叉树代码存在这里,具体的原理解释,以后有时间再补充

代码:

#include<iostream>
#define maxn 1000
using namespace std;

struct node
{
    int data;
    int height;
    node *lchild, *rchild;
};

int key[maxn];
int n;

int getheight(node* root)
{
    if(root != NULL)
    {
        return root->height;
    }else
    {
        return 0;
    }
}

void updataheight(node* &root)
{
    if(root != NULL)
    {
        root->height = max(getheight(root->lchild), getheight(root->rchild)) + 1;
    }
}

int getbalancefactor(node* root)
{
    return (getheight(root->lchild) - getheight(root->rchild));
}

void L(node* &root)
{
    node* temp = root->rchild;
    root->rchild = temp->lchild;
    temp->lchild = root;
    updataheight(root);
    updataheight(temp);
    root = temp;
}

void R(node* &root)
{
    node* temp = root->lchild;
    root->lchild = temp->rchild;
    temp->rchild = root;
    updataheight(root);
    updataheight(temp);
    root = temp;
}

node* newnode(int x)
{
    node* root = new node;
    root->data = x;
    root->height = 1;
    root->lchild = root->rchild = NULL;
    return root;
}

void insert(node* &root , int x)
{
    if(root == NULL)
    {
        root = newnode(x);
        return;
    }
    if(root->data == x)
    {
        return;
    }
    if(root->data > x)
    {
        insert(root->lchild, x);
        updataheight(root);

        if(getbalancefactor(root) == 2)
        {
            if(getbalancefactor(root->lchild) == 1)
            {
                R(root);
            }
            if(getbalancefactor(root->lchild) == -1)
            {
                L(root->lchild);
                R(root);
            }
        }

    }else if(root->data < x)
    {
        insert(root->rchild, x);
        updataheight(root);
        if(getbalancefactor(root) == -2)
        {
            if(getbalancefactor(root->rchild) == 1)
            {
                R(root->rchild);
                L(root);
            }
            if(getbalancefactor(root->rchild) == -1)
            {
                L(root);
            }
        }
    }
}

node* create(int key[], int n)
{
    node* root = NULL;
    for(int i = 0; i < n; i ++)
    {
        insert(root, key[i]);
    }
    return root;
}

void inorder(node* root)
{
    if(root == NULL)
    {
        return;
    }
    inorder(root->lchild);
    printf("%d ", root->data);
    inorder(root->rchild);
}

int main()
{
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        scanf("%d",&key[i]);
    }

    node* root = create(key, n);

    inorder(root);

    return 0;
}

测试用例:

输入 :  

8

10 20 30 7 14 25 40 48

输出:(经过处理的平衡二叉树的中序遍历)

7 10 14 20 25 30 40 48

猜你喜欢

转载自blog.csdn.net/young_Tao/article/details/81588269