PAT甲1123Is It a Complete AVL Tree (30) --AVL

来源:互联网 发布:打车软件对比分析 编辑:程序博客网 时间:2024/06/04 18:10

题意很简单,按avl数进行插入操作,最后进行层序遍历输出,判断是不是一个完全二叉树。

还是太菜,
avl没写出来。。。

#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;struct node {    int num, h;    node *left, *right;};int height(node *t) {    if (t == NULL)        return 0;    else        return t->h;}node *llRotate(node *r) {    node *t = r->left;    r->left =  t->right;    t->right = r;    r->h = max(height(r->left), height(r->right)) + 1;    t->h = max(height(t->left), height(t->right)) + 1;    return t;}node *rrRotate(node *r) {    node *t = r->right;    r->right =  t->left;    t->left = r;    r->h = max(height(r->left), height(r->right)) + 1;    t->h = max(height(t->left), height(t->right)) + 1;    return t;}node *lrRotate(node *r) {    r->left = rrRotate(r->left);    return llRotate(r);}node *rlRotate(node *r) {    r->right = llRotate(r->right);    return rrRotate(r);}node *insert(node *r, int x) {    if (r == NULL) {        node *t = (node *) malloc(sizeof(node));        t->num = x;        t->h = 1;        t->left = t->right = NULL;        //printf("%d\n", t->num);        return t;    }    if (x < r->num) {        r->left = insert(r->left, x);        if (height(r->left) - height(r->right) == 2) {            if (x < r->left->num)                r = llRotate(r);            else                r = lrRotate(r);        }    } else {        r->right = insert(r->right, x);        if (height(r->right) - height(r->left) == 2) {            if (x > r->right->num)                r = rrRotate(r);            else                r = rlRotate(r);        }    }    r->h = max(height(r->left), height(r->right)) + 1;    return r;}int main() {    int n;    scanf("%d", &n);    node *root = NULL;    for (int i = 0; i < n; i++) {        int x;        scanf("%d", &x);        root = insert(root, x);    }    queue<node*> q;    q.push(root);    bool flag = true, end = false;    bool first = true;    while (!q.empty()) {        node *t = q.front();        q.pop();        if (t->left)            q.push(t->left);        if (t->right)            q.push(t->right);        if (flag) {            if (!(t->left) && t->right)                 flag = false;            else if (!end && (!(t->left) || !(t->right)))                end = true;            else if (end && (t->left || t->right))                flag = false;        }        if (first) {            first = false;            printf("%d", t->num);        } else            printf(" %d", t->num);    }    putchar('\n');    puts(flag?"YES":"NO");    return 0;}
0 0