mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 01:06:30 +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) {
|
||||
if (node == nullptr) return new TreeNode(val);
|
||||
if (node == nullptr)
|
||||
return new TreeNode(val);
|
||||
/* 1. 查找插入位置,并插入结点 */
|
||||
if (val < node->val)
|
||||
node->left = insertHelper(node->left, val);
|
||||
|
@ -94,7 +95,8 @@ private:
|
|||
|
||||
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
|
||||
TreeNode* getInOrderNext(TreeNode* node) {
|
||||
if (node == nullptr) return node;
|
||||
if (node == nullptr)
|
||||
return node;
|
||||
// 循环访问左子结点,直到叶结点时为最小结点,跳出
|
||||
while (node->left != nullptr) {
|
||||
node = node->left;
|
||||
|
@ -104,7 +106,8 @@ private:
|
|||
|
||||
/* 递归删除结点(辅助方法) */
|
||||
TreeNode* removeHelper(TreeNode* node, int val) {
|
||||
if (node == nullptr) return nullptr;
|
||||
if (node == nullptr)
|
||||
return nullptr;
|
||||
/* 1. 查找结点,并删除之 */
|
||||
if (val < node->val)
|
||||
node->left = removeHelper(node->left, val);
|
||||
|
@ -126,8 +129,9 @@ private:
|
|||
} else {
|
||||
// 子结点数量 = 2 ,则将中序遍历的下个结点删除,并用该结点替换当前结点
|
||||
TreeNode* temp = getInOrderNext(node->right);
|
||||
int tempVal = temp->val;
|
||||
node->right = removeHelper(node->right, temp->val);
|
||||
node->val = temp->val;
|
||||
node->val = tempVal;
|
||||
}
|
||||
}
|
||||
updateHeight(node); // 更新结点高度
|
||||
|
@ -232,4 +236,4 @@ int main() {
|
|||
/* 查询结点 */
|
||||
TreeNode* node = avlTree.search(7);
|
||||
cout << "\n查找到的结点对象为 " << node << ",结点值 = " << node->val << endl;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue