PAT A1123 Is It a Complete AVL Tree (30分) (完全AVL树判定)
条评论PAT甲级:A1123 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 |
- 题意:给定插入结点的顺序,将其构建成平衡二叉树,输出这棵AVL树的层序遍历序列,并判断这棵树是不是完全二叉树。
- 分析:这题考察的是AVL树的构建和以及完全二叉树的判定。
- AVL本身是二叉搜索树,为了防止出现一边倒的情况,在插入结点到二叉搜索树的同时,对这棵树做相应调整,使这棵树的任意子树均保持左右子树高度差不超过1的特性。
- 对树的调整有4种形态。FIgure1所示,则直接从根节点右旋即可;Figure2所示,则是以88为根的结点需要左旋,而根结点70不需要调整;Figure3所示,则是先将以96为根的子树做右旋,把它调整为右侧较重的形状,之后对70为根的树左旋,刚好又能变得平衡;Figure4则是对以70为根的子树做右旋。
- AVL树构建完成后,层序遍历则是BFS这棵树就行了,这里还要解决问题的是在层序遍历的同时对其是否为完全二叉树做判断。因为这里事先就知道这棵树的结点数了,在对结点做输出的时候,每输出一个结点,cnt就会加1,这里对任意非叶子结点不管其左右孩子谁为空,都将其放进队列中,那么如果是完全二叉树,在遍历的过程中,即cnt未到达n的时队列中一定不会出现NULL元素,由此便可判断其是否为完全二叉树了。
1 |
|
- 本文链接:https://blog.charjin.top/2020/02/26/pat-A1123/
- 版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!
分享