AVL树是一种自平衡二叉搜索树,当插入或删除节点导致树失衡时,需要通过旋转操作使树恢复平衡。AVL树的单旋转操作包括左旋转和右旋转,本文以右旋转为例。
右旋转的基本思路是将左子树上的最大值(即左子树的根节点)上调至原来的根节点的位置,同时将原来的根节点作为右子树的根节点。具体实现步骤如下:
判断当前需要进行旋转的节点是否存在左子树。
如果存在,将左子树作为新的根节点。
此时,新的根节点的右子树应该等于原来的根节点的右子树。
同时,原来的根节点应该成为新根节点的右子树。
最后,更新新的根节点和原来的根节点的高度值和平衡因子。
代码示例:
typedef struct Node { int value; int height; int balance_factor; struct Node* left_child; struct Node* right_child; } Node;
Node* single_right_rotation(Node* root) { Node* new_root = root->left_child; root->left_child = new_root->right_child; new_root->right_child = root; calculate_height_and_balance_factor(root); calculate_height_and_balance_factor(new_root); return new_root; }
void calculate_height_and_balance_factor(Node* node) { int left_height = node->left_child ? node->left_child->height : -1; int right_height = node->right_child ? node->right_child->height : -1; int height = 1 + max(left_height, right_height); int balance_factor = right_height - left_height; node->height = height; node->balance_factor = balance_factor; }
下一篇:AVL树的插入与删除