1123 Is It a Complete AVL Tree (30 分)
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:
1 | 5 |
Sample Output 1:
1 | 70 63 88 61 65 |
Sample Input 2:
1 | 8 |
Sample Output 2:
1 | 88 65 96 61 70 90 120 68 |
作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
题目大意
给出一串数字,要求构造一颗avl树。然后中序遍历,判断是否为完全二叉树。
分析
如何建立avl树,参考1066 Root of AVL Tree (25 分)
遍历时,flag记录是否有结点已经不满。如果flag==1,且之后结点有了孩子,则不是一颗完全二叉树。