PAT (Advanced Level) Practice A1123 Is It a Complete AVL Tree (30 分)(PAT)(甲级 )(C++)(平衡二叉树、BFS)

版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/88549612

原题链接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 510, INF = 1<<30;

typedef struct BiTNode
{
    int data, height;
    struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;

BiTree newNode(int X)
{
    BiTree T = new BiTNode;
    T->data = X;
    T->height = 1;
    T->lChild = T->rChild = NULL;
    return T;
}

int getHeight(BiTree T)
{
    if(!T) return 0;
    return T->height;
}

void updataHeight(BiTree &T)
{
    if(!T) return ;
    T->height = 1 + max(getHeight(T->lChild), getHeight(T->rChild));
}

int getBalanceFactor(BiTree T)
{
    if(!T) return 0;
    return getHeight(T->lChild) - getHeight(T->rChild);
}

void LL(BiTree &A)
{
    BiTree B = A->lChild;
    A->lChild = B->rChild;
    B->rChild = A;
    updataHeight(A);
    updataHeight(B);
    A = B;
}

void RR(BiTree &A)
{
    BiTree B = A->rChild;
    A->rChild = B->lChild;
    B->lChild = A;
    updataHeight(A);
    updataHeight(B);
    A = B;
}

void LR(BiTree &A)
{
    RR(A->lChild);
    LL(A);
}

void RL(BiTree &A)
{
    LL(A->rChild);
    RR(A);
}

void insertNode(BiTree &T, int X)
{
    if(!T) T = newNode(X);
    else if(T->data > X)
    {
        insertNode(T->lChild, X);
        updataHeight(T);
        if(getBalanceFactor(T) == 2)
        {
            if(getBalanceFactor(T->lChild) == 1) LL(T);
            else if(getBalanceFactor(T->lChild) == -1) LR(T);
        }
    }
    else
    {
        insertNode(T->rChild, X);
        updataHeight(T);
        if(getBalanceFactor(T) == -2)
        {
            if(getBalanceFactor(T->rChild) == -1) RR(T);
            else if(getBalanceFactor(T->rChild) == 1) RL(T);
        }
    }
}

bool BFS(BiTree T)
{
    queue<BiTree> Q;
    Q.push(T);
    int flag = 0;
    printf("%d", T->data);
    while(!Q.empty())
    {
        T = Q.front();
        Q.pop();
        if(T->lChild)
        {
            printf(" %d", T->lChild->data);
            Q.push(T->lChild);
            if(flag) flag = 2;
        }
        else if(!flag) flag = 1;
        if(T->rChild)
        {
            printf(" %d", T->rChild->data);
            Q.push(T->rChild);
            if(flag) flag = 2;
        }
        else if(!flag) flag = 1;
    }
    printf("\n");
    if(flag == 2) return false;
    return true;
}

int main()
{
    int N, X;
    BiTree ROOT = NULL;
    scanf("%d", &N);
    for(int i=0; i<N; i++)
    {
        scanf("%d", &X);
        insertNode(ROOT, X);
    }
    if(BFS(ROOT)) printf("YES\n");
    else printf("NO\n");
	return 0;
}



猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/88549612