题目
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 tell the root of the resulting AVL tree.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=20) which is the total number of keys to be inserted. 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, print the root of the resulting AVL tree in one line.
Sample Input 1:
5
88 70 61 96 120
Sample Output 1:
70
Sample Input 2:
7
88 70 61 96 120 90 65
Sample Output 2:
88
思路
难题,考察平衡二叉树的建立,学了很多资料才搞明白,整理出了:
学习了柳神的代码:1066. Root of AVL Tree (25)-PAT甲级真题
自己根据理解和记忆又写了一遍,发现几个容易出错的点:
主函数循环体中:
//每插入一个节点都要更新根的值
root = insertVal(root, val);
插入节点函数insertVal中:
//若节点插入到左子树,则需更新root->l的值
if (val < root->val){
root->l = insertVal(root->l, val);
...
}
右旋函数rotateRight中:
Node* rotateRight(Node *root){
Node *p = root->l;
//下面两行代码次序不能颠倒
root->l = p->r;
p->r = root;
return p;

该博客介绍了如何使用C++实现PAT甲级真题1066题——建立AVL树。博主详细讨论了平衡二叉搜索树的概念,提供了插入操作和旋转规则,并通过例子解释了可能的错误点。文章包含多个参考资料链接,包括柳神的代码和一种试探法解决方案。
最低0.47元/天 解锁文章
4124

被折叠的 条评论
为什么被折叠?



