數據結構之二叉樹之平衡二叉樹

建立平衡二叉樹:

建利平衡二叉樹的關鍵的是要搞清楚關鍵步驟,首先判斷平衡因子,如果等於2或者-2,就要開始旋轉了,旋轉主要有四種類型,左左旋,左右旋,右右旋,右左旋。這裏就不一一解釋了,網上好多介紹如何旋轉的。

ps:對於我來說的難點。函數裏面調用函數,始終有點暈,搞不清楚原理。從網上看了好多代碼,最後終於搞清了原理,也最終寫出了平衡二叉樹

直接上代碼:

#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode
{
    int data;
    int bf;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//計算深度的函數,
int BiTDepth(BiTree root)
{
    int depth,rdepth,ldepth;
    if(!root) depth = 0;
    else
    {
        ldepth = BiTDepth(root->lchild);
        rdepth = BiTDepth(root->rchild);
        if(ldepth>rdepth)
        depth = ldepth + 1;
        else
            depth = rdepth +1;
    }
    return depth;
}
//計算平衡因子的函數。
int max(BiTree root)
{
    return BiTDepth(root->lchild)-BiTDepth(root->rchild);
}
BiTree  R_Rotate(BiTree root)
{
    BiTree L=root->lchild;                 /*L 指向*T 左子樹根結點*/
    root->lchild=L->rchild;                 /*L 的右子樹掛接*T 的左子樹*/
    L->rchild = root;
     root=L;
     return root;          /* *L 指向新的根結點*/
}
BiTree L_Rotate(BiTree root)
{
    BiTree Lr=root->rchild;                 /*Lr 指向*T 右子樹根結點*/
    root->rchild=Lr->lchild;                 /*L 的左子樹掛接*p 的右子樹*/
    Lr->lchild=root;
    root=Lr;
    //printf("%d ",root->rchild->data);
    return  root;                                    /* *L 指向新的根結點*/
}
//左平衡函數
//先判斷不平衡節點的下一個節點的平衡因子。如果平衡因子爲1,說明左邊插入,說明是左左型,
//如果是-1,說明是右右型,右邊插入
BiTree Leftbalance(BiTree root)
{
    BiTree l = root->lchild;
    switch(l->bf)
    {
    case 1:
        root = R_Rotate(root);
        break;
    case -1:
           l = L_Rotate(l);
           root->lchild = l;
            root = R_Rotate(root);
            break;
     }
    return root;

}
// 右平衡函數,同理左平衡函數。
BiTree Rightbalance(BiTree root)
{
    BiTree r = root->rchild;
    switch(r->bf)
    {
    case -1:
        root = L_Rotate(root);
        break;
    case 1:
        r = R_Rotate(r);
        root->rchild = r;
        root = L_Rotate(root);
        break;
    }
    return root;
}
//創建二叉樹的過程。函數裏面調用函數
//新建的節點平衡因子一定爲0 ,建好後,返回上一個節點。即新節點的雙親節點,並計算該節點的平衡因子,
//不斷向上找。直到找到平衡因子爲2或-2的節點,然後進行平衡。
 BiTree Creat(BiTree root,int m)
 {
     if(root == NULL)
     {
         root = (BiTree)malloc(sizeof(BiTNode));
         root->data = m;
         root->lchild = root->rchild = NULL;
         root-> bf = 0;
         return root;
     }
     else if(m<root->data)
     {
         root->lchild = Creat(root->lchild,m);
          root->bf = max(root);
         if(root->bf==2)
            root = Leftbalance(root);
     }
     else
     {
         root->rchild = Creat(root->rchild,m);
            root->bf = max(root);
         if(root->bf==-2)
            root = Rightbalance(root);
     }
     return root;
 }
int main()
{
    int n;
    scanf("%d",&n);
    BiTree root = NULL;
    while(n--)
    {
        int m;
        scanf("%d",&m);
        root = Creat(root,m);
    }
    printf("%d\n",root->data);
    return 0;
}


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