diff --git a/codes/cpp/chapter_heap/heap.cpp b/codes/cpp/chapter_heap/heap.cpp index 8d32d17ff6..ef1cec882a 100644 --- a/codes/cpp/chapter_heap/heap.cpp +++ b/codes/cpp/chapter_heap/heap.cpp @@ -63,4 +63,4 @@ int main() cout << "输入列表并建立小顶堆后" << endl; PrintUtil::printHeap(minHeap); return 0; -} +} \ No newline at end of file diff --git a/codes/cpp/chapter_heap/my_heap.cpp b/codes/cpp/chapter_heap/my_heap.cpp new file mode 100644 index 0000000000..dd463678af --- /dev/null +++ b/codes/cpp/chapter_heap/my_heap.cpp @@ -0,0 +1,170 @@ +#include "../include/include.hpp" + +/* 最大堆类 */ +class MaxHeap { +private: + // 使用 vector 而非数组,这样无需考虑扩容问题 + vector maxHeap; + + /* 获取左子结点索引 */ + int left(int i) { + return 2 * i + 1; + } + + /* 获取右子结点索引 */ + int right(int i) { + return 2 * i + 2; + } + + /* 获取父结点索引 */ + int parent(int i) { + return (i - 1) / 2; // 向下整除 + } + + /* 交换元素 */ + void swap(int i, int j) { + int a = maxHeap[i], + b = maxHeap[j], + tmp = a; + maxHeap[i] = b; + maxHeap[j] = tmp; + } + + /* 从结点 i 开始,从底至顶堆化 */ + void siftUp(int i) { + while (true) { + // 获取结点 i 的父结点 + int p = parent(i); + // 当“越过根结点”或“结点无需修复”时,结束堆化 + if (p < 0 || maxHeap[i] <= maxHeap[i]) + break; + // 交换两结点 + swap(i, p); + // 循环向上堆化 + i = p; + } + } + + /* 从结点 i 开始,从顶至底堆化 */ + void siftDown(int i) { + while (true) { + // 判断结点 i, l, r 中值最大的结点,记为 ma + int l = left(i), r = right(i), ma = i; + if (l < size() && maxHeap[l] > maxHeap[ma]) + ma = l; + if (r < size() && maxHeap[r] > maxHeap[ma]) + ma = r; + // 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出 + if (ma == i) break; + // 交换两结点 + swap(i, ma); + // 循环向下堆化 + i = ma; + } + } + +public: + /* 构造函数,建立空堆 */ + MaxHeap() = default; + + /* 构造函数,根据输入列表建堆 */ + MaxHeap(vector nums) { + // 将列表元素原封不动添加进堆 + maxHeap = nums; + // 堆化除叶结点以外的其他所有结点 + for (int i = parent(size() - 1); i >= 0; i--) { + siftDown(i); + } + } + + /* 获取堆大小 */ + int size() { + return maxHeap.size(); + } + + /* 判断堆是否为空 */ + bool isEmpty() { + return size() == 0; + } + + /* 访问堆顶元素 */ + int peek() { + return maxHeap.front(); + } + + /* 元素入堆 */ + void push(int val) { + // 添加结点 + maxHeap.push_back(val); + // 从底至顶堆化 + siftUp(size() - 1); + } + + /* 元素出堆 */ + int poll() { + // 判空处理 + if (isEmpty()) + throw out_of_range("堆已空\n"); + // 交换根结点与最右叶结点(即交换首元素与尾元素) + swap(0, size() - 1); + // 删除结点 + int val = maxHeap.back(); + maxHeap.pop_back(); + // 从顶至底堆化 + siftDown(0); + // 返回堆顶元素 + return val; + } + + /* 打印堆(二叉树) */ + void print() { + cout << "堆的数组表示:" << endl; + PrintUtil::printVector(this->maxHeap); + cout << "堆的树状表示:" << endl; + TreeNode *tree = vecToTree(this->maxHeap); + PrintUtil::printTree(tree); + freeMemoryTree(tree); + } +}; + +void testPush(MaxHeap &maxHeap, int val) { + maxHeap.push(val); // 元素入堆 + cout << "\n添加元素 " << val << " 后" << endl; + maxHeap.print(); +} + +void testPoll(MaxHeap &maxHeap) { + int val = maxHeap.poll(); // 堆顶元素出堆 + cout << "出堆元素为 " << val << endl; + maxHeap.print(); +} + +int main() { + /* 初始化大顶堆 */ + MaxHeap maxHeap({9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2}); + cout << "\n输入列表并建堆后" << endl; + maxHeap.print(); + + /* 获取堆顶元素 */ + int peek = maxHeap.peek(); + cout << "\n堆顶元素为 " << peek << endl; + + /* 元素入堆 */ + int val = 7; + maxHeap.push(val); + cout << "\n元素 " << val << " 入堆后" << endl; + maxHeap.print(); + + /* 堆顶元素出堆 */ + peek = maxHeap.poll(); + cout << "\n堆顶元素 " << peek << " 出堆后" << endl; + maxHeap.print(); + + /* 获取堆大小 */ + int size = maxHeap.size(); + cout << "\n堆元素数量为 " << size << endl; + + /* 判断堆是否为空 */ + bool isEmpty = maxHeap.isEmpty(); + cout << "\n堆是否为空 " << isEmpty << endl; +} \ No newline at end of file diff --git a/codes/cpp/chapter_tree/avl_tree.cpp b/codes/cpp/chapter_tree/avl_tree.cpp new file mode 100644 index 0000000000..e657c242f4 --- /dev/null +++ b/codes/cpp/chapter_tree/avl_tree.cpp @@ -0,0 +1,235 @@ +/** + * File: avl_tree.cpp + * Created Time: 2023-2-3 + * Author: what-is-me (whatisme@outlook.jp) + */ + +#include "../include/include.hpp" + +/* AVL 树 */ +class AVLTree { +public: + TreeNode* root; // 根节点 +private: + /* 更新结点高度 */ + void updateHeight(TreeNode* node) { + // 结点高度等于最高子树高度 + 1 + node->height = max(height(node->left), height(node->right)) + 1; + } + + /* 右旋操作 */ + 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; + } + + /* 左旋操作 */ + 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; + } + + /* 执行旋转操作,使该子树重新恢复平衡 */ + 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; + } + + /* 递归插入结点(辅助函数) */ + TreeNode* insertHelper(TreeNode* node, int val) { + if (node == nullptr) return new TreeNode(val); + /* 1. 查找插入位置,并插入结点 */ + if (val < node->val) + node->left = insertHelper(node->left, val); + else if (val > node->val) + node->right = insertHelper(node->right, val); + else + return node; // 重复结点不插入,直接返回 + updateHeight(node); // 更新结点高度 + /* 2. 执行旋转操作,使该子树重新恢复平衡 */ + node = rotate(node); + // 返回子树的根节点 + return node; + } + + /* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */ + TreeNode* getInOrderNext(TreeNode* node) { + if (node == nullptr) return node; + // 循环访问左子结点,直到叶结点时为最小结点,跳出 + while (node->left != nullptr) { + node = node->left; + } + return node; + } + + /* 递归删除结点(辅助函数) */ + TreeNode* removeHelper(TreeNode* node, int val) { + if (node == nullptr) return nullptr; + /* 1. 查找结点,并删除之 */ + if (val < node->val) + node->left = removeHelper(node->left, val); + else if (val > node->val) + node->right = removeHelper(node->right, val); + else { + if (node->left == nullptr || node->right == nullptr) { + TreeNode* child = node->left != nullptr ? node->left : node->right; + // 子结点数量 = 0 ,直接删除 node 并返回 + if (child == nullptr) { + delete node; + return nullptr; + } + // 子结点数量 = 1 ,直接删除 node + else { + delete node; + node = child; + } + } else { + // 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点 + TreeNode* temp = getInOrderNext(node->right); + node->right = removeHelper(node->right, temp->val); + node->val = temp->val; + } + } + updateHeight(node); // 更新结点高度 + /* 2. 执行旋转操作,使该子树重新恢复平衡 */ + node = rotate(node); + // 返回子树的根节点 + return node; + } + +public: + /* 获取结点高度 */ + int height(TreeNode* node) { + // 空结点高度为 -1 ,叶结点高度为 0 + return node == nullptr ? -1 : node->height; + } + + /* 获取平衡因子 */ + int balanceFactor(TreeNode* node) { + // 空结点平衡因子为 0 + if (node == nullptr) return 0; + // 结点平衡因子 = 左子树高度 - 右子树高度 + return height(node->left) - height(node->right); + } + + /* 插入结点 */ + TreeNode* insert(int val) { + root = insertHelper(root, val); + return root; + } + + /* 删除结点 */ + TreeNode* remove(int val) { + root = removeHelper(root, val); + return root; + } + + /* 查找结点 */ + TreeNode* search(int val) { + TreeNode* cur = root; + // 循环查找,越过叶结点后跳出 + while (cur != nullptr) { + // 目标结点在 cur 的右子树中 + if (cur->val < val) + cur = cur->right; + // 目标结点在 cur 的左子树中 + else if (cur->val > val) + cur = cur->left; + // 找到目标结点,跳出循环 + else + break; + } + // 返回目标结点 + return cur; + } + + /*构造函数*/ + AVLTree() : root(nullptr) {} + + /*析构函数*/ + ~AVLTree() { + freeMemoryTree(root); + } +}; + +void testInsert(AVLTree& tree, int val) { + tree.insert(val); + cout << "\n插入结点 " << val << " 后,AVL 树为" << endl; + PrintUtil::printTree(tree.root); +} + +void testRemove(AVLTree& tree, int val) { + tree.remove(val); + cout << "\n删除结点 " << val << " 后,AVL 树为" << endl; + PrintUtil::printTree(tree.root); +} +int main() { + /* 初始化空 AVL 树 */ + AVLTree avlTree; + + /* 插入结点 */ + // 请关注插入结点后,AVL 树是如何保持平衡的 + testInsert(avlTree, 1); + testInsert(avlTree, 2); + testInsert(avlTree, 3); + testInsert(avlTree, 4); + testInsert(avlTree, 5); + testInsert(avlTree, 8); + testInsert(avlTree, 7); + testInsert(avlTree, 9); + testInsert(avlTree, 10); + testInsert(avlTree, 6); + + /* 插入重复结点 */ + testInsert(avlTree, 7); + + /* 删除结点 */ + // 请关注删除结点后,AVL 树是如何保持平衡的 + testRemove(avlTree, 8); // 删除度为 0 的结点 + testRemove(avlTree, 5); // 删除度为 1 的结点 + testRemove(avlTree, 4); // 删除度为 2 的结点 + + /* 查询结点 */ + TreeNode* node = avlTree.search(7); + cout << "\n查找到的结点对象为 " << node << ",结点值 = " << node->val << endl; +} \ No newline at end of file diff --git a/docs/chapter_heap/heap.md b/docs/chapter_heap/heap.md index 555aad2362..acbf6fa353 100644 --- a/docs/chapter_heap/heap.md +++ b/docs/chapter_heap/heap.md @@ -287,7 +287,23 @@ comments: true === "C++" ```cpp title="my_heap.cpp" + // 使用 vector 而非数组,这样无需考虑扩容问题 + vector maxHeap; + /* 获取左子结点索引 */ + int left(int i) { + return 2 * i + 1; + } + + /* 获取右子结点索引 */ + int right(int i) { + return 2 * i + 2; + } + + /* 获取父结点索引 */ + int parent(int i) { + return (i - 1) / 2; // 向下整除 + } ``` === "Python" @@ -400,7 +416,10 @@ comments: true === "C++" ```cpp title="my_heap.cpp" - + /* 访问堆顶元素 */ + int peek() { + return maxHeap.front(); + } ``` === "Python" @@ -513,7 +532,28 @@ comments: true === "C++" ```cpp title="my_heap.cpp" + /* 元素入堆 */ + void push(int val) { + // 添加结点 + maxHeap.push_back(val); + // 从底至顶堆化 + siftUp(size() - 1); + } + /* 从结点 i 开始,从底至顶堆化 */ + void siftUp(int i) { + while (true) { + // 获取结点 i 的父结点 + int p = parent(i); + // 当“越过根结点”或“结点无需修复”时,结束堆化 + if (p < 0 || maxHeap[i] <= maxHeap[i]) + break; + // 交换两结点 + swap(i, p); + // 循环向上堆化 + i = p; + } + } ``` === "Python" @@ -691,7 +731,39 @@ comments: true === "C++" ```cpp title="my_heap.cpp" + /* 元素出堆 */ + int poll() { + // 判空处理 + if (isEmpty()) + throw out_of_range("堆已空\n"); + // 交换根结点与最右叶结点(即交换首元素与尾元素) + swap(0, size() - 1); + // 删除结点 + int val = maxHeap.back(); + maxHeap.pop_back(); + // 从顶至底堆化 + siftDown(0); + // 返回堆顶元素 + return val; + } + /* 从结点 i 开始,从顶至底堆化 */ + void siftDown(int i) { + while (true) { + // 判断结点 i, l, r 中值最大的结点,记为 ma + int l = left(i), r = right(i), ma = i; + if (l < size() && maxHeap[l] > maxHeap[ma]) + ma = l; + if (r < size() && maxHeap[r] > maxHeap[ma]) + ma = r; + // 若结点 i 最大或索引 l, r 越界,则无需继续堆化,跳出 + if (ma == i) break; + // 交换两结点 + swap(i, ma); + // 循环向下堆化 + i = ma; + } + } ``` === "Python" @@ -843,7 +915,16 @@ comments: true === "C++" ```cpp title="my_heap.cpp" - + /* 构造函数,根据输入列表建堆 */ + MaxHeap(vector nums) { + // 将列表元素原封不动添加进堆 + maxHeap = nums; + // 堆化除叶结点以外的其他所有结点 + for (int i = parent(size() - 1); i >= 0; i--) { + siftDown(i); + } + } + // Tip: std::make_heap() 函数可以原地建堆。 ``` === "Python" diff --git a/docs/chapter_tree/avl_tree.md b/docs/chapter_tree/avl_tree.md index 20b6329592..b258b8af17 100644 --- a/docs/chapter_tree/avl_tree.md +++ b/docs/chapter_tree/avl_tree.md @@ -31,18 +31,27 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit ```java title="avl_tree.java" /* AVL 树结点类 */ class TreeNode { - public int val; // 结点值 - public int height; // 结点高度 - public TreeNode left; // 左子结点 - public TreeNode right; // 右子结点 + public int val; // 结点值 + public int height; // 结点高度 + public TreeNode left; // 左子结点 + public TreeNode right; // 右子结点 public TreeNode(int x) { val = x; } } - ``` + +```` === "C++" ```cpp title="avl_tree.cpp" - + /* AVL 树结点类 */ + struct TreeNode { + int val{}; // 结点值 + int height = 0; // 结点高度 + TreeNode *left{}; // 左子结点 + TreeNode *right{}; // 右子结点 + TreeNode() = default; + explicit TreeNode(int x) : val(x){} + }; ``` === "Python" @@ -55,7 +64,10 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit self.height = 0 # 结点高度 self.left = left # 左子结点引用 self.right = right # 右子结点引用 - ``` + + + +```` === "Go" @@ -72,20 +84,22 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit === "JavaScript" ```js title="avl_tree.js" - - ``` + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + + + +```` === "C#" @@ -115,7 +129,8 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit height = 0 } } - ``` + +```` === "Zig" @@ -128,23 +143,36 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit === "Java" ```java title="avl_tree.java" - /* 获取结点高度 */ + /* 获取结点高度 */ int height(TreeNode node) { // 空结点高度为 -1 ,叶结点高度为 0 return node == null ? -1 : node.height; } - + /* 更新结点高度 */ void updateHeight(TreeNode node) { // 结点高度等于最高子树高度 + 1 - node.height = Math.max(height(node.left), height(node.right)) + 1; + node.height = Math.max(height(node.left), height(node.right)) + 1; } - ``` + + + +```` === "C++" ```cpp title="avl_tree.cpp" - + /* 获取结点高度 */ + int height(TreeNode* node) { + // 空结点高度为 -1 ,叶结点高度为 0 + return node == nullptr ? -1 : node->height; + } + + /* 更新结点高度 */ + void updateHeight(TreeNode* node) { + // 结点高度等于最高子树高度 + 1 + node->height = max(height(node->left), height(node->right)) + 1; + } ``` === "Python" @@ -156,12 +184,13 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit if node is not None: return node.height return -1 - + """ 更新结点高度 """ def __update_height(self, node: Optional[TreeNode]): # 结点高度等于最高子树高度 + 1 node.height = max([self.height(node.left), self.height(node.right)]) + 1 - ``` + +```` === "Go" @@ -191,20 +220,22 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit === "JavaScript" ```js title="avl_tree.js" - - ``` + + + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + +```` === "C#" @@ -215,7 +246,7 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit // 空结点高度为 -1 ,叶结点高度为 0 return node == null ? -1 : node.height; } - + /* 更新结点高度 */ private void updateHeight(TreeNode node) { @@ -238,7 +269,10 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit // 结点高度等于最高子树高度 + 1 node?.height = max(height(node: node?.left), height(node: node?.right)) + 1 } - ``` + + + +```` === "Zig" @@ -253,19 +287,26 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit === "Java" ```java title="avl_tree.java" - /* 获取结点平衡因子 */ + /* 获取结点平衡因子 */ public int balanceFactor(TreeNode node) { // 空结点平衡因子为 0 if (node == null) return 0; // 结点平衡因子 = 左子树高度 - 右子树高度 return height(node.left) - height(node.right); } - ``` + +```` === "C++" ```cpp title="avl_tree.cpp" - + /* 获取平衡因子 */ + int balanceFactor(TreeNode* node) { + // 空结点平衡因子为 0 + if (node == nullptr) return 0; + // 结点平衡因子 = 左子树高度 - 右子树高度 + return height(node->left) - height(node->right); + } ``` === "Python" @@ -278,7 +319,10 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit return 0 # 结点平衡因子 = 左子树高度 - 右子树高度 return self.height(node.left) - self.height(node.right) - ``` + + + +```` === "Go" @@ -297,20 +341,22 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit === "JavaScript" ```js title="avl_tree.js" - - ``` + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + + + +```` === "C#" @@ -335,7 +381,8 @@ G. M. Adelson-Velsky 和 E. M. Landis 在其 1962 年发表的论文 "An algorit // 结点平衡因子 = 左子树高度 - 右子树高度 return height(node: node.left) - height(node: node.right) } - ``` + +```` === "Zig" @@ -358,15 +405,22 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 如下图所示(结点下方为「平衡因子」),从底至顶看,二叉树中首个失衡结点是 **结点 3**。我们聚焦在以该失衡结点为根结点的子树上,将该结点记为 `node` ,将其左子节点记为 `child` ,执行「右旋」操作。完成右旋后,该子树已经恢复平衡,并且仍然为二叉搜索树。 === "Step 1" - ![right_rotate_step1](avl_tree.assets/right_rotate_step1.png) + +![right_rotate_step1](avl_tree.assets/right_rotate_step1.png) + === "Step 2" - ![right_rotate_step2](avl_tree.assets/right_rotate_step2.png) + +![right_rotate_step2](avl_tree.assets/right_rotate_step2.png) + === "Step 3" - ![right_rotate_step3](avl_tree.assets/right_rotate_step3.png) + +![right_rotate_step3](avl_tree.assets/right_rotate_step3.png) + === "Step 4" - ![right_rotate_step4](avl_tree.assets/right_rotate_step4.png) -进而,如果结点 `child` 本身有右子结点(记为 `grandChild`),则需要在「右旋」中添加一步:将 `grandChild` 作为 `node` 的左子结点。 +![right_rotate_step4](avl_tree.assets/right_rotate_step4.png) + +进而,如果结点 `child` 本身有右子结点(记为 `grandChild` ),则需要在「右旋」中添加一步:将 `grandChild` 作为 `node` 的左子结点。 ![right_rotate_with_grandchild](avl_tree.assets/right_rotate_with_grandchild.png) @@ -375,7 +429,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 === "Java" ```java title="avl_tree.java" - /* 右旋操作 */ + /* 右旋操作 */ TreeNode rightRotate(TreeNode node) { TreeNode child = node.left; TreeNode grandChild = child.right; @@ -388,12 +442,27 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 返回旋转后子树的根节点 return child; } - ``` + + + +```` === "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; + } ``` === "Python" @@ -411,7 +480,8 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 self.__update_height(child) # 返回旋转后子树的根节点 return child - ``` + +```` === "Go" @@ -434,20 +504,22 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 === "JavaScript" ```js title="avl_tree.js" - - ``` + + + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + +```` === "C#" @@ -466,7 +538,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 返回旋转后子树的根节点 return child; } - + ``` === "Swift" @@ -485,7 +557,10 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 返回旋转后子树的根节点 return child } - ``` + + + +```` === "Zig" @@ -499,7 +574,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 ![left_rotate](avl_tree.assets/left_rotate.png) -同理,若结点 `child` 本身有左子结点(记为 `grandChild`),则需要在「左旋」中添加一步:将 `grandChild` 作为 `node` 的右子结点。 +同理,若结点 `child` 本身有左子结点(记为 `grandChild` ),则需要在「左旋」中添加一步:将 `grandChild` 作为 `node` 的右子结点。 ![left_rotate_with_grandchild](avl_tree.assets/left_rotate_with_grandchild.png) @@ -508,7 +583,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 === "Java" ```java title="avl_tree.java" - /* 左旋操作 */ + /* 左旋操作 */ private TreeNode leftRotate(TreeNode node) { TreeNode child = node.right; TreeNode grandChild = child.left; @@ -521,12 +596,25 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 返回旋转后子树的根节点 return child; } - ``` + +```` === "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; + } ``` === "Python" @@ -544,7 +632,10 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 self.__update_height(child) # 返回旋转后子树的根节点 return child - ``` + + + +```` === "Go" @@ -567,20 +658,22 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 === "JavaScript" ```js title="avl_tree.js" - - ``` + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + + + +```` === "C#" @@ -617,7 +710,8 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 返回旋转后子树的根节点 return child } - ``` + +```` === "Zig" @@ -690,12 +784,43 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 平衡树,无需旋转,直接返回 return node; } - ``` + + + +```` === "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; + } ``` === "Python" @@ -725,7 +850,8 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 return self.__left_rotate(node) # 平衡树,无需旋转,直接返回 return node - ``` + +```` === "Go" @@ -765,20 +891,22 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 === "JavaScript" ```js title="avl_tree.js" - - ``` + + + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + +```` === "C#" @@ -855,7 +983,10 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 平衡树,无需旋转,直接返回 return node } - ``` + + + +```` === "Zig" @@ -877,7 +1008,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 root = insertHelper(root, val); return root; } - + /* 递归插入结点(辅助函数) */ TreeNode insertHelper(TreeNode node, int val) { if (node == null) return new TreeNode(val); @@ -887,19 +1018,41 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 else if (val > node.val) node.right = insertHelper(node.right, val); else - return node; // 重复结点不插入,直接返回 - updateHeight(node); // 更新结点高度 + return node; // 重复结点不插入,直接返回 + updateHeight(node); // 更新结点高度 /* 2. 执行旋转操作,使该子树重新恢复平衡 */ node = rotate(node); // 返回子树的根节点 return node; } - ``` + +```` === "C++" ```cpp title="avl_tree.cpp" - + /* 插入结点 */ + TreeNode* insert(int val) { + root = insertHelper(root, val); + return root; + } + + /* 递归插入结点(辅助函数) */ + TreeNode* insertHelper(TreeNode* node, int val) { + if (node == nullptr) return new TreeNode(val); + /* 1. 查找插入位置,并插入结点 */ + if (val < node->val) + node->left = insertHelper(node->left, val); + else if (val > node->val) + node->right = insertHelper(node->right, val); + else + return node; // 重复结点不插入,直接返回 + updateHeight(node); // 更新结点高度 + /* 2. 执行旋转操作,使该子树重新恢复平衡 */ + node = rotate(node); + // 返回子树的根节点 + return node; + } ``` === "Python" @@ -909,7 +1062,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 def insert(self, val) -> TreeNode: self.root = self.__insert_helper(self.root, val) return self.root - + """ 递归插入结点(辅助函数)""" def __insert_helper(self, node: Optional[TreeNode], val: int) -> TreeNode: if node is None: @@ -926,7 +1079,10 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 self.__update_height(node) # 2. 执行旋转操作,使该子树重新恢复平衡 return self.__rotate(node) - ``` + + + +```` === "Go" @@ -962,20 +1118,22 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 === "JavaScript" ```js title="avl_tree.js" - - ``` + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + + + +```` === "C#" @@ -986,7 +1144,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 root = insertHelper(root, val); return root; } - + /* 递归插入结点(辅助函数) */ private TreeNode? insertHelper(TreeNode? node, int val) { @@ -1036,7 +1194,8 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 返回子树的根节点 return node } - ``` + +```` === "Zig" @@ -1056,7 +1215,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 root = removeHelper(root, val); return root; } - + /* 递归删除结点(辅助函数) */ TreeNode removeHelper(TreeNode node, int val) { if (node == null) return null; @@ -1081,18 +1240,60 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 node.val = temp.val; } } - updateHeight(node); // 更新结点高度 + updateHeight(node); // 更新结点高度 /* 2. 执行旋转操作,使该子树重新恢复平衡 */ node = rotate(node); // 返回子树的根节点 return node; } - ``` + + + +```` === "C++" ```cpp title="avl_tree.cpp" - + /* 删除结点 */ + TreeNode* remove(int val) { + root = removeHelper(root, val); + return root; + } + + /* 递归删除结点(辅助函数) */ + TreeNode* removeHelper(TreeNode* node, int val) { + if (node == nullptr) return nullptr; + /* 1. 查找结点,并删除之 */ + if (val < node->val) + node->left = removeHelper(node->left, val); + else if (val > node->val) + node->right = removeHelper(node->right, val); + else { + if (node->left == nullptr || node->right == nullptr) { + TreeNode* child = node->left != nullptr ? node->left : node->right; + // 子结点数量 = 0 ,直接删除 node 并返回 + if (child == nullptr) { + delete node; + return nullptr; + } + // 子结点数量 = 1 ,直接删除 node + else { + delete node; + node = child; + } + } else { + // 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点 + TreeNode* temp = getInOrderNext(node->right); + node->right = removeHelper(node->right, temp->val); + node->val = temp->val; + } + } + updateHeight(node); // 更新结点高度 + /* 2. 执行旋转操作,使该子树重新恢复平衡 */ + node = rotate(node); + // 返回子树的根节点 + return node; + } ``` === "Python" @@ -1102,7 +1303,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 def remove(self, val: int): root = self.__remove_helper(self.root, val) return root - + """ 递归删除结点(辅助函数) """ def __remove_helper(self, node: Optional[TreeNode], val: int) -> Optional[TreeNode]: if node is None: @@ -1129,7 +1330,8 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 self.__update_height(node) # 2. 执行旋转操作,使该子树重新恢复平衡 return self.__rotate(node) - ``` + +```` === "Go" @@ -1139,7 +1341,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 root := removeHelper(t.root, val) return root } - + /* 递归删除结点(辅助函数) */ func removeHelper(node *TreeNode, val int) *TreeNode { if node == nil { @@ -1182,20 +1384,22 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 === "JavaScript" ```js title="avl_tree.js" - - ``` + + + +```` === "TypeScript" ```typescript title="avl_tree.ts" - + ``` === "C" ```c title="avl_tree.c" - - ``` + +```` === "C#" @@ -1206,7 +1410,7 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 root = removeHelper(root, val); return root; } - + /* 递归删除结点(辅助函数) */ private TreeNode? removeHelper(TreeNode? node, int val) { @@ -1289,7 +1493,10 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 // 返回子树的根节点 return node } - ``` + + + +```` === "Zig" @@ -1303,8 +1510,8 @@ AVL 树的独特之处在于「旋转 Rotation」的操作,其可 **在不影 ## 7.4.4. AVL 树典型应用 -- 组织存储大型数据,适用于高频查找、低频增删场景; -- 用于建立数据库中的索引系统; +- 组织存储大型数据,适用于高频查找、低频增删场景; +- 用于建立数据库中的索引系统; !!! question "为什么红黑树比 AVL 树更受欢迎?" - 红黑树的平衡条件相对宽松,因此在红黑树中插入与删除结点所需的旋转操作相对更少,结点增删操作相比 AVL 树的效率更高。 +红黑树的平衡条件相对宽松,因此在红黑树中插入与删除结点所需的旋转操作相对更少,结点增删操作相比 AVL 树的效率更高。