|
|
@@ -14,13 +14,15 @@ BSTNode::BSTNode(int key) :
|
|
|
key_(key),
|
|
|
parent_(std::weak_ptr<BSTNode>()),
|
|
|
left_(nullptr),
|
|
|
- right_(nullptr) {} // add a height_
|
|
|
+ right_(nullptr),
|
|
|
+ height_(1) {} // add a height_
|
|
|
|
|
|
BSTNode::BSTNode(int key, std::weak_ptr<BSTNode> parent) :
|
|
|
key_(key),
|
|
|
parent_(parent),
|
|
|
left_(nullptr),
|
|
|
- right_(nullptr) {}
|
|
|
+ right_(nullptr),
|
|
|
+ height_(1) {}
|
|
|
|
|
|
bool BSTNode::IsLeaf() const {
|
|
|
return left_ == nullptr && right_ == nullptr;
|
|
|
@@ -203,6 +205,7 @@ void AVLCommands::Insert(int key) {
|
|
|
}
|
|
|
|
|
|
bool AVLCommands::Delete(int key) {
|
|
|
+ // base BST delete
|
|
|
std::shared_ptr<BSTNode> currentNode = root_;
|
|
|
while (currentNode != nullptr) {
|
|
|
if (currentNode->key_ == key) {
|
|
|
@@ -225,6 +228,33 @@ bool AVLCommands::Delete(int key) {
|
|
|
currentNode = (key < currentNode->key_) ?
|
|
|
currentNode->left_ : currentNode->right_;
|
|
|
}
|
|
|
+
|
|
|
+ // update height of current node
|
|
|
+ currentNode->height_ = 1 + max(height(currentNode->left_), height(currentNode->right_));
|
|
|
+
|
|
|
+ // Update balance factor of this ancestor's node
|
|
|
+ int currentNodeBalance = getBalance(currentNode);
|
|
|
+
|
|
|
+ // Check if unbalanced
|
|
|
+ // Left Left Case
|
|
|
+ if (currentNodeBalance > 1 && getBalance(currentNode->left_) >= 0)
|
|
|
+ rightRotate(currentNode);
|
|
|
+
|
|
|
+ // Right Right Case
|
|
|
+ if (currentNodeBalance < -1 && getBalance(currentNode->right_) <= 0)
|
|
|
+ leftRotate(currentNode);
|
|
|
+
|
|
|
+ // Left Right Case
|
|
|
+ if (currentNodeBalance > 1 && getBalance(currentNode->left_) < 0) {
|
|
|
+ currentNode->left_ = leftRotate(currentNode->left_);
|
|
|
+ rightRotate(currentNode);
|
|
|
+ }
|
|
|
+
|
|
|
+ // Right Left Case
|
|
|
+ if (currentNodeBalance < -1 && getBalance(currentNode->right_) > 0) {
|
|
|
+ currentNode->right_ = rightRotate(currentNode->right_);
|
|
|
+ leftRotate(currentNode);
|
|
|
+ }
|
|
|
return false;
|
|
|
}
|
|
|
|