Selaa lähdekoodia

changed rightRotate to follow the marginally correct leftRotate's algorithm

Natalie Pueyo 8 vuotta sitten
vanhempi
commit
b76c3b2693
1 muutettua tiedostoa jossa 17 lisäystä ja 15 poistoa
  1. 17 15
      program3/AVLCommands.cpp

+ 17 - 15
program3/AVLCommands.cpp

@@ -146,22 +146,26 @@ std::shared_ptr<BSTNode> AVLCommands::rightRotate(std::shared_ptr<BSTNode> curre
 		std::cout << "Can't rotate on an empty node!" << std::endl;
 		return currentNode;
 	}
-	std::cout << "First, Right Rotate!" << std::endl;
-	std::cout << "Top: " << currentNode->key_;
-	std::cout << ", Middle: " << currentNode->left_->key_;
-	std::cout << ", Last: " << currentNode->left_->right_->key_ << std::endl;
+
+	std::cout << "Right Rotate at node " << currentNode->key_ << std::endl;
+
 	std::shared_ptr<BSTNode> x = currentNode->left_;
-	std::cout << "Does the current node have a left node?" << std::endl;
-	std::shared_ptr<BSTNode> T2 = x->right_;
-	std::cout << "Does the current node's left node have a right node?" << std::endl;
-	// Perform rotation
+	currentNode->left_ = x->right_;
 	x->right_ = currentNode;
-	currentNode->left_ = T2;
 
-	// Update heights
-	currentNode->height_ = max(height(currentNode->left_), height(currentNode->right_))+1;
-	x->height_ = max(height(x->left_), height(x->right_))+1;
+	std::shared_ptr<BSTNode> parentSubroot = currentNode->parent_.lock();
+
+	if (parentSubroot == nullptr) {
+		root_ = x;
+		x->parent_.reset();
+	} else {
+		parentSubroot->left_ = x;
+	}
 
+	currentNode = x;
+	std::cout << "hello" << std::endl;
+	// Update heights
+	height(root_);
 	// Return new root
 	return x;
 }
@@ -191,10 +195,8 @@ std::shared_ptr<BSTNode> AVLCommands::leftRotate(std::shared_ptr<BSTNode> curren
 	}
 
 	currentNode = y;
-	std::cout << "hello" << std::endl; 
+	std::cout << "hello" << std::endl;
   //  Update heights
-  //currentNode->height_ = max(height(currentNode->left_), height(currentNode->right_))+1;
-  //y->height_ = max(height(y->left_), height(y->right_))+1;
 	height(root_);
   // Return new root
   return y;