AVLCommands.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // balance and height functions based on code from
  2. // http://www.sanfoundry.com/cpp-program-implement-avl-trees/
  3. // Finding elements based on code from
  4. // http://www.cplusplus.com/forum/beginner/54835/
  5. #include <cassert>
  6. #include <iostream>
  7. #include <string>
  8. #include <queue>
  9. #include "json.hpp"
  10. #include "AVLCommands.h"
  11. BSTNode::BSTNode(int key) :
  12. key_(key),
  13. parent_(std::weak_ptr<BSTNode>()),
  14. left_(nullptr),
  15. right_(nullptr),
  16. height_(0),
  17. balance_(0) {} // add a height_
  18. BSTNode::BSTNode(int key, std::weak_ptr<BSTNode> parent) :
  19. key_(key),
  20. parent_(parent),
  21. left_(nullptr),
  22. right_(nullptr),
  23. height_(0),
  24. balance_(0) {}
  25. bool BSTNode::IsLeaf() const {
  26. return left_ == nullptr && right_ == nullptr;
  27. }
  28. bool BSTNode::HasLeftChild() const {
  29. return left_ != nullptr;
  30. }
  31. bool BSTNode::HasRightChild() const {
  32. return right_ != nullptr;
  33. }
  34. void BSTNode::DeleteChild(std::shared_ptr<BSTNode> v) {
  35. if (left_ == v) {
  36. left_ = nullptr;
  37. } else if (right_ == v) {
  38. right_ = nullptr;
  39. } else {
  40. std::cerr << "BSTNode::DeleteChild Error: non-child passed as argument\n";
  41. exit(EXIT_FAILURE);
  42. }
  43. }
  44. void BSTNode::ReplaceChild(std::shared_ptr<BSTNode> v, std::shared_ptr<BSTNode> u) {
  45. if (left_ == u || right_ == u) {
  46. std::cerr << "BSTNode::ReplaceChild Error: child passed as replacement\n";
  47. }
  48. if (left_ == v) {
  49. left_ = u;
  50. u->parent_ = v->parent_;
  51. } else if (right_ == v) {
  52. right_ = u;
  53. u->parent_ = v->parent_;
  54. } else {
  55. std::cerr << "BSTNode::ReplaceChild Error: non-child passed as argument\n";
  56. exit(EXIT_FAILURE);
  57. }
  58. }
  59. AVLCommands::AVLCommands() : root_(nullptr), size_(0) {} // add height here?
  60. int AVLCommands::max(int a, int b) {
  61. return (a > b)? a : b;
  62. }
  63. int AVLCommands::height(std::shared_ptr<BSTNode> currentNode) {
  64. if (root_ == nullptr) {
  65. return 0;
  66. }
  67. int leftHeight, rightHeight, heightMax;
  68. if (currentNode != nullptr) {
  69. if (currentNode->left_ != nullptr) {
  70. leftHeight = height(currentNode->left_);
  71. } else {
  72. leftHeight = -1;
  73. }
  74. if (currentNode->right_ != nullptr) {
  75. rightHeight = height(currentNode->right_);
  76. } else {
  77. rightHeight = -1;
  78. }
  79. heightMax = 1 + max(leftHeight, rightHeight);
  80. currentNode->height_ = heightMax;
  81. // update balance for each node
  82. currentNode->balance_ = leftHeight - rightHeight;
  83. }
  84. return currentNode->height_;
  85. }
  86. int AVLCommands::getBalance(std::shared_ptr<BSTNode> currentNode) {
  87. if (root_ == nullptr) {
  88. return 0;
  89. }
  90. int leftHeight, rightHeight, balanceFactor;
  91. if (currentNode != nullptr) {
  92. if (currentNode->left_ != nullptr) {
  93. leftHeight = height(currentNode->left_);
  94. } else {
  95. leftHeight = -1;
  96. }
  97. if (currentNode->right_ != nullptr) {
  98. rightHeight = height(currentNode->right_);
  99. } else {
  100. rightHeight = -1;
  101. }
  102. balanceFactor = leftHeight - rightHeight;
  103. }
  104. return balanceFactor;
  105. }
  106. std::shared_ptr<BSTNode> AVLCommands::rightRotate(std::shared_ptr<BSTNode> currentNode){
  107. std::cout << "Right Rotate!" << std::endl;
  108. std::shared_ptr<BSTNode> x = currentNode->left_;
  109. std::shared_ptr<BSTNode> T2 = x->right_;
  110. // Perform rotation
  111. x->right_ = currentNode;
  112. currentNode->left_ = T2;
  113. // Update heights
  114. currentNode->height_ = max(height(currentNode->left_), height(currentNode->right_))+1;
  115. x->height_ = max(height(x->left_), height(x->right_))+1;
  116. // Return new root
  117. return x;
  118. return currentNode;
  119. }
  120. std::shared_ptr<BSTNode> AVLCommands::leftRotate(std::shared_ptr<BSTNode> currentNode){
  121. std::cout << "Left Rotate!" << std::endl;
  122. std::shared_ptr<BSTNode> y = currentNode->right_;
  123. std::shared_ptr<BSTNode> T2 = y->left_;
  124. // Perform rotation
  125. y->left_ = currentNode;
  126. currentNode->right_ = T2;
  127. // Update heights
  128. currentNode->height_ = max(height(currentNode->left_), height(currentNode->right_))+1;
  129. y->height_ = max(height(y->left_), height(y->right_))+1;
  130. // Return new root
  131. return y;
  132. }
  133. void AVLCommands::printTree(){
  134. printTree(root_);
  135. }
  136. void AVLCommands::printTree(std::shared_ptr<BSTNode> currentNode){
  137. if (root_ == nullptr) {
  138. std::cout << "tree is empty" << std::endl;
  139. return;
  140. } else {
  141. std::cout << "key: " << currentNode->key_ << std::endl;
  142. std::cout << "height: " << currentNode->height_ << std::endl;
  143. std::cout << "balance: " << currentNode->balance_ << std::endl;
  144. if (currentNode->left_ != nullptr) {
  145. std::cout << "left" << std::endl;
  146. printTree(currentNode->left_);
  147. }
  148. if (currentNode->right_ != nullptr) {
  149. std::cout << "right" << std::endl;
  150. printTree(currentNode->right_);
  151. }
  152. }
  153. }
  154. void AVLCommands::Insert(int key) {
  155. std::cout << "Inserting new key: " << key << std::endl;
  156. // BST insertion
  157. if (root_ == nullptr) {
  158. root_ = std::make_shared<BSTNode>(key);
  159. size_++;
  160. return;
  161. }
  162. std::shared_ptr<BSTNode> currentNode = root_, lastNode = nullptr;
  163. while (currentNode != nullptr) {
  164. lastNode = currentNode;
  165. currentNode = (key < currentNode->key_) ?
  166. currentNode->left_ : currentNode->right_;
  167. }
  168. if (key < lastNode->key_) {
  169. lastNode->left_ = std::make_shared<BSTNode>(key, lastNode);
  170. } else {
  171. lastNode->right_ = std::make_shared<BSTNode>(key, lastNode);
  172. }
  173. size_++;
  174. // update height and balance of the tree
  175. height(root_);
  176. std::cout << "Rotation to be preformed:" << std::endl;
  177. // Check if unbalanced
  178. // Left Left Case
  179. if (lastNode->balance_ > 1 && key < lastNode->left_->key_) {
  180. std::cout << "Left-Left" << std::endl;
  181. rightRotate(lastNode);
  182. }
  183. // Right Right Case
  184. if (lastNode->balance_ < -1 && key > lastNode->right_->key_) {
  185. std::cout << "Right-Right" << std::endl;
  186. leftRotate(lastNode);
  187. }
  188. // Left Right Case
  189. if (lastNode->balance_ > 1 && key > lastNode->left_->key_) {
  190. std::cout << "Left-Right" << std::endl;
  191. lastNode->left_ = leftRotate(lastNode->left_);
  192. rightRotate(lastNode);
  193. }
  194. // Right Left Case
  195. if (lastNode->balance_ < -1 && key < lastNode->right_->key_) {
  196. std::cout << "Right-Left" << std::endl;
  197. lastNode->right_ = rightRotate(lastNode->right_);
  198. leftRotate(lastNode);
  199. }
  200. }
  201. bool AVLCommands::Delete(int key) {
  202. // base BST delete
  203. std::shared_ptr<BSTNode> currentNode = root_;
  204. while (currentNode != nullptr) {
  205. if (currentNode->key_ == key) {
  206. if (currentNode->IsLeaf()) {
  207. DeleteLeaf(currentNode);
  208. } else if (currentNode->left_ == nullptr) {
  209. assert(currentNode->right_ != nullptr);
  210. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  211. parent->ReplaceChild(currentNode, currentNode->right_);
  212. size_--; assert(size_ >= 0);
  213. } else if (currentNode->right_ == nullptr) {
  214. assert(currentNode->left_ != nullptr);
  215. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  216. parent->ReplaceChild(currentNode, currentNode->left_);
  217. size_--; assert(size_ >= 0);
  218. } else {
  219. currentNode->key_ = DeleteMin(currentNode);
  220. }
  221. }
  222. currentNode = (key < currentNode->key_) ?
  223. currentNode->left_ : currentNode->right_;
  224. }
  225. std::cout << "current node value: " << currentNode->key_ << std::endl;
  226. // update height of current node
  227. std::cout << "delete height update attempt..." << std::endl;
  228. currentNode->height_ = 1 + max(height(currentNode->left_), height(currentNode->right_));
  229. std::cout << "New height: " << currentNode->height_ << std::endl;
  230. std::cout << "delete height update attempt success" << std::endl;
  231. // Update balance factor of this ancestor's node
  232. std::cout << "delete balance update attempt..." << std::endl;
  233. int currentNodeBalance = getBalance(currentNode);
  234. std::cout << "delete balance update attempt success!" << std::endl;
  235. // Check if unbalanced
  236. // Left Left Case
  237. if (currentNodeBalance > 1 && getBalance(currentNode->left_) >= 0)
  238. rightRotate(currentNode);
  239. // Right Right Case
  240. if (currentNodeBalance < -1 && getBalance(currentNode->right_) <= 0)
  241. leftRotate(currentNode);
  242. // Left Right Case
  243. if (currentNodeBalance > 1 && getBalance(currentNode->left_) < 0) {
  244. currentNode->left_ = leftRotate(currentNode->left_);
  245. rightRotate(currentNode);
  246. }
  247. // Right Left Case
  248. if (currentNodeBalance < -1 && getBalance(currentNode->right_) > 0) {
  249. currentNode->right_ = rightRotate(currentNode->right_);
  250. leftRotate(currentNode);
  251. }
  252. return false;
  253. }
  254. int AVLCommands::DeleteMin() {
  255. return DeleteMin(root_);
  256. }
  257. void AVLCommands::DeleteLeaf(std::shared_ptr<BSTNode> currentNode) {
  258. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  259. if (parent == nullptr) {
  260. // Delete root
  261. root_ = nullptr;
  262. size_--; assert(size_ == 0);
  263. } else {
  264. if (parent->right_ == currentNode) {
  265. parent->right_ = nullptr;
  266. } else if (parent->left_ == currentNode) {
  267. parent->left_ = nullptr;
  268. } else {
  269. std::cerr << "BST::DeleteLeaf Error: inconsistent state\n";
  270. }
  271. size_--; assert(size_ >= 0);
  272. }
  273. }
  274. int AVLCommands::DeleteMin(std::shared_ptr<BSTNode> currentNode) {
  275. std::shared_ptr<BSTNode> lastNode = nullptr;
  276. while (currentNode != nullptr) {
  277. lastNode = currentNode;
  278. currentNode = currentNode->left_;
  279. }
  280. int result = lastNode->key_;
  281. std::shared_ptr<BSTNode> parent = lastNode->parent_.lock();
  282. if (parent == nullptr) {
  283. // lastNode is root
  284. if (lastNode->right_ != nullptr) {
  285. root_ = lastNode->right_;
  286. lastNode->right_->parent_.reset();
  287. } else {
  288. root_ = nullptr;
  289. }
  290. } else {
  291. // lastNode under the root
  292. if (lastNode->right_ != nullptr) {
  293. parent->left_ = lastNode->right_;
  294. lastNode->right_->parent_ = parent;
  295. } else {
  296. parent->left_ = nullptr;
  297. }
  298. }
  299. size_--; assert(size_ >= 0);
  300. return result;
  301. }
  302. size_t AVLCommands::size() const {
  303. return size_;
  304. }
  305. bool AVLCommands::empty() const {
  306. return size_ == 0;
  307. }
  308. bool AVLCommands::Find(int key) const {
  309. std::shared_ptr<BSTNode> currentNode = root_;
  310. while (currentNode != nullptr) {
  311. if (currentNode->key_ == key) {
  312. return true;
  313. }
  314. currentNode = (key < currentNode->key_) ?
  315. currentNode->left_ : currentNode->right_;
  316. }
  317. return false;
  318. }
  319. std::string AVLCommands::JSON() const {
  320. nlohmann::json result;
  321. std::queue< std::shared_ptr<BSTNode> > nodes;
  322. if (root_ != nullptr) {
  323. result["root"] = root_->key_;
  324. nodes.push(root_);
  325. while (!nodes.empty()) {
  326. auto v = nodes.front();
  327. nodes.pop();
  328. std::string key = std::to_string(v->key_);
  329. //std::string height = std::to_string(v->height_);
  330. //result[key]["height"] = height;
  331. result[key]["left"] = v->left_->key_;
  332. if (v->left_ != nullptr) {
  333. result[key]["left"] = v->left_->key_;
  334. nodes.push(v->left_);
  335. }
  336. if (v->right_ != nullptr) {
  337. result[key]["right"] = v->right_->key_;
  338. nodes.push(v->right_);
  339. }
  340. if (v->parent_.lock() != nullptr) {
  341. result[key]["parent"] = v->parent_.lock()->key_;
  342. } else {
  343. result[key]["root"] = true;
  344. }
  345. }
  346. }
  347. result["size"] = size_;
  348. return result.dump(2) + "\n";
  349. }