Sfoglia il codice sorgente

rr rotation almost correct though when there are a lot of nodes under the ones being rotated I'm getting a seg fault

Natalie Pueyo 8 anni fa
parent
commit
45cbabe3c7
2 ha cambiato i file con 24 aggiunte e 13 eliminazioni
  1. 14 13
      program3/AVLCommands.cpp
  2. 10 0
      program3/test.cpp

+ 14 - 13
program3/AVLCommands.cpp

@@ -172,29 +172,30 @@ std::shared_ptr<BSTNode> AVLCommands::leftRotate(std::shared_ptr<BSTNode> curren
 		std::cout << "Can't rotate on an empty node!" << std::endl;
 		return currentNode;
 	}
-	std::cout << "Left Rotate!" << std::endl;
+	std::cout << "Left Rotate at node " << currentNode->key_ << std::endl;
 
 	std::shared_ptr<BSTNode> y = currentNode->right_;
+	currentNode->right_ = y->left_;
 	y->left_ = currentNode;
 
-	std::shared_ptr<BSTNode> T2 = y->left_;
-	currentNode->right_ = T2;
-
-
+	std::shared_ptr<BSTNode> parentSubroot = currentNode->parent_.lock();
 	std::cout << "New subtree root: " << y->key_ << std::endl;
-	std::cout << "New left: " << y->left_->key_ << std::endl;
-	std::cout << "New right: " << y->right_->key_ << std::endl;
-	std::cout << "Old subtree root: " << currentNode->key_ << std::endl;
-	//std::cout << "Old left: " << currentNode->left_->key_ << std::endl;
-	std::cout << "Old right: " << currentNode->right_->key_ << std::endl;
+	//std::cout << "New left: " << y->left_->key_ << std::endl;
+	//std::cout << "New right: " << y->right_->key_ << std::endl;
 
-	std::cout << "New root: " << root_->key_ << std::endl;
+	if (parentSubroot == nullptr) {
+		root_ = y;
+		y->parent_.reset();
+	} else {
+		parentSubroot->right_ = y;
+	}
 
+	currentNode = y;
+	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(y);
-	printTree();
+	height(root_);
   // Return new root
   return y;
 }

+ 10 - 0
program3/test.cpp

@@ -1,4 +1,5 @@
 // Driver program to test above functions
+#include <iostream>
 #include "AVLCommands.h"
 
 int main()
@@ -6,23 +7,32 @@ int main()
     AVLCommands avl;
     avl.Insert(2);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(3);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(4);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(5);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(1);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(6);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(7);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(8);
     avl.printTree();
+    std::cout << std::endl;
     avl.Insert(9);
     //avl.Insert(50);
     avl.printTree();
+    std::cout << std::endl;
     //avl.Delete(15);
     return 0;
 }