mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-24 12:06:07 +00:00
Fix Repo
This commit is contained in:
@@ -303,13 +303,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
/* 获取平衡因子 */
|
||||
int balanceFactor(TreeNode* node) {
|
||||
// 空结点平衡因子为 0
|
||||
if (node == nullptr) return 0;
|
||||
// 结点平衡因子 = 左子树高度 - 右子树高度
|
||||
return height(node->left) - height(node->right);
|
||||
}
|
||||
[class]{AVLTree}-[func]{balanceFactor}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
@@ -436,19 +430,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
/* 右旋操作 */
|
||||
TreeNode* rightRotate(TreeNode* node) {
|
||||
TreeNode* child = node->left;
|
||||
TreeNode* grandChild = child->right;
|
||||
// 以 child 为原点,将 node 向右旋转
|
||||
child->right = node;
|
||||
node->left = grandChild;
|
||||
// 更新结点高度
|
||||
updateHeight(node);
|
||||
updateHeight(child);
|
||||
// 返回旋转后子树的根结点
|
||||
return child;
|
||||
}
|
||||
[class]{AVLTree}-[func]{rightRotate}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
@@ -581,19 +563,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
/* 左旋操作 */
|
||||
TreeNode* leftRotate(TreeNode* node) {
|
||||
TreeNode* child = node->right;
|
||||
TreeNode* grandChild = child->left;
|
||||
// 以 child 为原点,将 node 向左旋转
|
||||
child->left = node;
|
||||
node->right = grandChild;
|
||||
// 更新结点高度
|
||||
updateHeight(node);
|
||||
updateHeight(child);
|
||||
// 返回旋转后子树的根结点
|
||||
return child;
|
||||
}
|
||||
[class]{AVLTree}-[func]{leftRotate}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
@@ -750,35 +720,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影
|
||||
=== "C++"
|
||||
|
||||
```cpp title="avl_tree.cpp"
|
||||
/* 执行旋转操作,使该子树重新恢复平衡 */
|
||||
TreeNode* rotate(TreeNode* node) {
|
||||
// 获取结点 node 的平衡因子
|
||||
int _balanceFactor = balanceFactor(node);
|
||||
// 左偏树
|
||||
if (_balanceFactor > 1) {
|
||||
if (balanceFactor(node->left) >= 0) {
|
||||
// 右旋
|
||||
return rightRotate(node);
|
||||
} else {
|
||||
// 先左旋后右旋
|
||||
node->left = leftRotate(node->left);
|
||||
return rightRotate(node);
|
||||
}
|
||||
}
|
||||
// 右偏树
|
||||
if (_balanceFactor < -1) {
|
||||
if (balanceFactor(node->right) <= 0) {
|
||||
// 左旋
|
||||
return leftRotate(node);
|
||||
} else {
|
||||
// 先右旋后左旋
|
||||
node->right = rightRotate(node->right);
|
||||
return leftRotate(node);
|
||||
}
|
||||
}
|
||||
// 平衡树,无需旋转,直接返回
|
||||
return node;
|
||||
}
|
||||
[class]{AVLTree}-[func]{rotate}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
Reference in New Issue
Block a user