|
|
@ -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); // 更新结点高度
|
|
|
@ -232,4 +236,4 @@ int main() {
|
|
|
|
/* 查询结点 */
|
|
|
|
/* 查询结点 */
|
|
|
|
TreeNode* node = avlTree.search(7);
|
|
|
|
TreeNode* node = avlTree.search(7);
|
|
|
|
cout << "\n查找到的结点对象为 " << node << ",结点值 = " << node->val << endl;
|
|
|
|
cout << "\n查找到的结点对象为 " << node << ",结点值 = " << node->val << endl;
|
|
|
|
}
|
|
|
|
}
|
|
|
|