mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-26 01:36:29 +08:00
Fix avl_tree.cpp
This commit is contained in:
parent
0840bc2043
commit
28f3c98697
1 changed files with 9 additions and 5 deletions
|
@ -77,7 +77,8 @@ private:
|
||||||
|
|
||||||
/* 递归插入结点(辅助方法) */
|
/* 递归插入结点(辅助方法) */
|
||||||
TreeNode* insertHelper(TreeNode* node, int val) {
|
TreeNode* insertHelper(TreeNode* node, int val) {
|
||||||
if (node == nullptr) return new TreeNode(val);
|
if (node == nullptr)
|
||||||
|
return new TreeNode(val);
|
||||||
/* 1. 查找插入位置,并插入结点 */
|
/* 1. 查找插入位置,并插入结点 */
|
||||||
if (val < node->val)
|
if (val < node->val)
|
||||||
node->left = insertHelper(node->left, val);
|
node->left = insertHelper(node->left, val);
|
||||||
|
@ -94,7 +95,8 @@ private:
|
||||||
|
|
||||||
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
|
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
|
||||||
TreeNode* getInOrderNext(TreeNode* node) {
|
TreeNode* getInOrderNext(TreeNode* node) {
|
||||||
if (node == nullptr) return node;
|
if (node == nullptr)
|
||||||
|
return node;
|
||||||
// 循环访问左子结点,直到叶结点时为最小结点,跳出
|
// 循环访问左子结点,直到叶结点时为最小结点,跳出
|
||||||
while (node->left != nullptr) {
|
while (node->left != nullptr) {
|
||||||
node = node->left;
|
node = node->left;
|
||||||
|
@ -104,7 +106,8 @@ private:
|
||||||
|
|
||||||
/* 递归删除结点(辅助方法) */
|
/* 递归删除结点(辅助方法) */
|
||||||
TreeNode* removeHelper(TreeNode* node, int val) {
|
TreeNode* removeHelper(TreeNode* node, int val) {
|
||||||
if (node == nullptr) return nullptr;
|
if (node == nullptr)
|
||||||
|
return nullptr;
|
||||||
/* 1. 查找结点,并删除之 */
|
/* 1. 查找结点,并删除之 */
|
||||||
if (val < node->val)
|
if (val < node->val)
|
||||||
node->left = removeHelper(node->left, val);
|
node->left = removeHelper(node->left, val);
|
||||||
|
@ -126,8 +129,9 @@ private:
|
||||||
} else {
|
} else {
|
||||||
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
|
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
|
||||||
TreeNode* temp = getInOrderNext(node->right);
|
TreeNode* temp = getInOrderNext(node->right);
|
||||||
|
int tempVal = temp->val;
|
||||||
node->right = removeHelper(node->right, temp->val);
|
node->right = removeHelper(node->right, temp->val);
|
||||||
node->val = temp->val;
|
node->val = tempVal;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
updateHeight(node); // 更新结点高度
|
updateHeight(node); // 更新结点高度
|
||||||
|
|
Loading…
Reference in a new issue