PAT甲级1123

来源:互联网 发布:数据挖掘入门 编辑:程序博客网 时间:2024/05/01 14:06

1123. Is It a Complete AVL Tree (30)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

    

    

Now given a sequence of insertions, you are supposed to output the level-order traversal sequence of the resulting AVL tree, and to tell if it is a complete binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<= 20). Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, insert the keys one by one into an initially empty AVL tree. Then first print in a line the level-order traversal sequence of the resulting AVL tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line. Then in the next line, print "YES" if the tree is complete, or "NO" if not.

Sample Input 1:
588 70 61 63 65
Sample Output 1:
70 63 88 61 65YES
Sample Input 2:
888 70 61 96 120 90 65 68
Sample Output 2:
88 65 96 61 70 90 120 68NO

#include<cstdio>#include<algorithm>#include<queue>using namespace std;struct Node{int data;int height;Node*l, *r;Node():height(1),l(NULL),r(NULL){}};int getHeight(Node*n){if (!n)return 0;return n->height;}int getBalanceFactor(Node*n){return getHeight(n->l) - getHeight(n->r);}void updateHeight(Node*n){n->height = max(getHeight(n->l), getHeight(n->r)) + 1;}void L(Node*&n){Node*temp = n->r;n->r = temp->l;temp->l = n;updateHeight(n);updateHeight(temp);n = temp;}void R(Node*&n){Node*temp = n->l;n->l = temp->r;temp->r = n;updateHeight(n);updateHeight(temp);n = temp;}void insert(Node*&n,int x)//修改了指针本身要加引用{if (!n){n = new Node;n->data = x;return;}if (x < n->data){insert(n->l, x);updateHeight(n);if (getBalanceFactor(n) == 2){if (getBalanceFactor(n->l) == 1){R(n);}else if (getBalanceFactor(n->l) == -1){L(n->l);R(n);}}}else {insert(n->r, x);updateHeight(n);if (getBalanceFactor(n) == -2){if (getBalanceFactor(n->r) == -1){L(n);}else if (getBalanceFactor(n->r) == 1){R(n->r);L(n);}}}}int maxindex = -1;void dfs(Node*n,int index){if (!n)return;maxindex = max(maxindex, index);dfs(n->l, 2 * index);dfs(n->r, 2 * index+1);}void levelOrder(Node*root){queue<Node*> Q;Q.push(root);bool first = true;while (!Q.empty()){Node*n = Q.front();Q.pop();if (first){printf("%d", n->data);first = false;}elseprintf(" %d", n->data);if (n->l)Q.push(n->l);if (n->r)Q.push(n->r);}}int main(){int N;scanf("%d", &N);Node*root = NULL;int x;for (int i = 0; i < N; i++){scanf("%d", &x);insert(root, x);}levelOrder(root);printf("\n");dfs(root, 1);if (maxindex == N){printf("YES");}elseprintf("NO");return 0;}

0 0