AVLCommands.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. //std::cout << "Updating the height..." << std::endl;
  65. //std::cout << "height: " << currentNode->height_ << std::endl;
  66. if (root_ == nullptr) {
  67. return 0;
  68. }
  69. int leftHeight, rightHeight, heightMax;
  70. if (currentNode != nullptr) {
  71. if (currentNode->left_ != nullptr) {
  72. leftHeight = height(currentNode->left_);
  73. } else {
  74. leftHeight = -1;
  75. }
  76. if (currentNode->right_ != nullptr) {
  77. rightHeight = height(currentNode->right_);
  78. } else {
  79. rightHeight = -1;
  80. }
  81. heightMax = 1 + max(leftHeight, rightHeight);
  82. currentNode->height_ = heightMax;
  83. // update balance for each node
  84. currentNode->balance_ = leftHeight - rightHeight;
  85. }
  86. return currentNode->height_;
  87. }
  88. void AVLCommands::balance(std::shared_ptr<BSTNode> currentNode) {
  89. if (currentNode == nullptr) {
  90. return;
  91. }
  92. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  93. if (parent != nullptr) {
  94. //std::cout << "parent node key: " << parent->key_ << std::endl;
  95. std::cout << "balanceFactor at balance: " << parent->balance_ <<std::endl;
  96. //std::cout << "Rotation to be preformed:" << std::endl;
  97. if (parent->balance_ > 1) {
  98. if (parent->key_ < parent->left_->key_) {
  99. std::cout << "Left-Left" << std::endl;
  100. rightRotate(parent);
  101. return;
  102. } else if (parent->key_ > parent->left_->key_) {
  103. std::cout << "Left-Right" << std::endl;
  104. parent->left_ = leftRotate(parent->left_);
  105. rightRotate(parent);
  106. return;
  107. }
  108. } else if (parent->balance_ < -1) {
  109. if (parent->key_ < parent->right_->key_) {
  110. std::cout << "Right-Right" << std::endl;
  111. std::cout << "Current Node key input: " << parent->key_ << std::endl;
  112. leftRotate(parent);
  113. return;
  114. } else if (parent->key_ > parent->right_->key_) {
  115. std::cout << "Right-Left" << std::endl;
  116. parent->right_ = rightRotate(parent->right_);
  117. leftRotate(parent);
  118. return;
  119. }
  120. }
  121. balance(parent);
  122. }
  123. return;
  124. }
  125. std::shared_ptr<BSTNode> AVLCommands::rightRotate(std::shared_ptr<BSTNode> currentNode){
  126. printTree();
  127. if (currentNode == nullptr) {
  128. std::cout << "Can't rotate on an empty node!" << std::endl;
  129. return currentNode;
  130. }
  131. std::cout << "First, Right Rotate!" << std::endl;
  132. std::cout << "Top: " << currentNode->key_;
  133. std::cout << ", Middle: " << currentNode->left_->key_;
  134. std::cout << ", Last: " << currentNode->left_->right_->key_ << std::endl;
  135. std::shared_ptr<BSTNode> x = currentNode->left_;
  136. std::cout << "Does the current node have a left node?" << std::endl;
  137. std::shared_ptr<BSTNode> T2 = x->right_;
  138. std::cout << "Does the current node's left node have a right node?" << std::endl;
  139. // Perform rotation
  140. x->right_ = currentNode;
  141. currentNode->left_ = T2;
  142. // Update heights
  143. currentNode->height_ = max(height(currentNode->left_), height(currentNode->right_))+1;
  144. x->height_ = max(height(x->left_), height(x->right_))+1;
  145. // Return new root
  146. return x;
  147. }
  148. // Takes the root of the tree to be left rotated and rotates it to provide new root
  149. std::shared_ptr<BSTNode> AVLCommands::leftRotate(std::shared_ptr<BSTNode> currentNode){
  150. if (currentNode == nullptr) {
  151. std::cout << "Can't rotate on an empty node!" << std::endl;
  152. return currentNode;
  153. }
  154. std::cout << "Left Rotate!" << std::endl;
  155. std::shared_ptr<BSTNode> y = currentNode->right_;
  156. y->left_ = currentNode;
  157. std::shared_ptr<BSTNode> T2 = y->left_;
  158. currentNode->right_ = T2;
  159. std::cout << "New subtree root: " << y->key_ << std::endl;
  160. std::cout << "New left: " << y->left_->key_ << std::endl;
  161. std::cout << "New right: " << y->right_->key_ << std::endl;
  162. std::cout << "Old subtree root: " << currentNode->key_ << std::endl;
  163. //std::cout << "Old left: " << currentNode->left_->key_ << std::endl;
  164. std::cout << "Old right: " << currentNode->right_->key_ << std::endl;
  165. std::cout << "New root: " << root_->key_ << std::endl;
  166. // Update heights
  167. //currentNode->height_ = max(height(currentNode->left_), height(currentNode->right_))+1;
  168. //y->height_ = max(height(y->left_), height(y->right_))+1;
  169. //height(y);
  170. printTree();
  171. // Return new root
  172. return y;
  173. }
  174. void AVLCommands::printTree(){
  175. printTree(root_);
  176. }
  177. void AVLCommands::printTree(std::shared_ptr<BSTNode> currentNode){
  178. if (root_ == nullptr) {
  179. std::cout << "tree is empty" << std::endl;
  180. return;
  181. } else {
  182. std::cout << "key: " << currentNode->key_ << std::endl;
  183. std::cout << "height: " << currentNode->height_ << std::endl;
  184. std::cout << "balance: " << currentNode->balance_ << std::endl;
  185. if (currentNode->parent_.lock() != nullptr) {
  186. std::cout << "parent: " << currentNode->parent_.lock()->key_ << std::endl;
  187. }
  188. if (currentNode->left_ != nullptr) {
  189. std::cout << "left" << std::endl;
  190. printTree(currentNode->left_);
  191. }
  192. if (currentNode->right_ != nullptr) {
  193. std::cout << "right" << std::endl;
  194. printTree(currentNode->right_);
  195. }
  196. }
  197. }
  198. void AVLCommands::Insert(int key) {
  199. std::cout << "Inserting new key: " << key << std::endl;
  200. // BST insertion
  201. if (root_ == nullptr) {
  202. root_ = std::make_shared<BSTNode>(key);
  203. size_++;
  204. return;
  205. }
  206. std::shared_ptr<BSTNode> currentNode = root_, lastNode = nullptr;
  207. while (currentNode != nullptr) {
  208. lastNode = currentNode;
  209. currentNode = (key < currentNode->key_) ?
  210. currentNode->left_ : currentNode->right_;
  211. }
  212. if (key < lastNode->key_) {
  213. lastNode->left_ = std::make_shared<BSTNode>(key, lastNode);
  214. } else {
  215. lastNode->right_ = std::make_shared<BSTNode>(key, lastNode);
  216. }
  217. size_++;
  218. // update height and balance of the tree
  219. height(root_);
  220. balance(lastNode);
  221. /*
  222. // Check if unbalanced
  223. // Left Left Case
  224. if (lastNode->balance_ > 1 && key < lastNode->left_->key_) {
  225. std::cout << "Left-Left" << std::endl;
  226. rightRotate(lastNode);
  227. }
  228. // Right Right Case
  229. if (lastNode->balance_ < -1 && key > lastNode->right_->key_) {
  230. std::cout << "Right-Right" << std::endl;
  231. leftRotate(lastNode);
  232. }
  233. // Left Right Case
  234. if (lastNode->balance_ > 1 && key > lastNode->left_->key_) {
  235. std::cout << "Left-Right" << std::endl;
  236. lastNode->left_ = leftRotate(lastNode->left_);
  237. rightRotate(lastNode);
  238. }
  239. // Right Left Case
  240. if (lastNode->balance_ < -1 && key < lastNode->right_->key_) {
  241. std::cout << "Right-Left" << std::endl;
  242. lastNode->right_ = rightRotate(lastNode->right_);
  243. leftRotate(lastNode);
  244. }
  245. */
  246. }
  247. bool AVLCommands::Delete(int key) {
  248. // base BST delete
  249. std::shared_ptr<BSTNode> currentNode = root_;
  250. while (currentNode != nullptr) {
  251. if (currentNode->key_ == key) {
  252. if (currentNode->IsLeaf()) {
  253. DeleteLeaf(currentNode);
  254. } else if (currentNode->left_ == nullptr) {
  255. assert(currentNode->right_ != nullptr);
  256. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  257. parent->ReplaceChild(currentNode, currentNode->right_);
  258. size_--; assert(size_ >= 0);
  259. } else if (currentNode->right_ == nullptr) {
  260. assert(currentNode->left_ != nullptr);
  261. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  262. parent->ReplaceChild(currentNode, currentNode->left_);
  263. size_--; assert(size_ >= 0);
  264. } else {
  265. currentNode->key_ = DeleteMin(currentNode);
  266. }
  267. }
  268. currentNode = (key < currentNode->key_) ?
  269. currentNode->left_ : currentNode->right_;
  270. }
  271. std::cout << "current node value: " << currentNode->key_ << std::endl;
  272. // update height of current node
  273. std::cout << "delete height update attempt..." << std::endl;
  274. currentNode->height_ = 1 + max(height(currentNode->left_), height(currentNode->right_));
  275. std::cout << "New height: " << currentNode->height_ << std::endl;
  276. std::cout << "delete height update attempt success" << std::endl;
  277. // Update balance factor of this ancestor's node
  278. /*
  279. // Check if unbalanced
  280. // Left Left Case
  281. if (currentNodeBalance > 1 && getBalance(currentNode->left_) >= 0)
  282. rightRotate(currentNode);
  283. // Right Right Case
  284. if (currentNodeBalance < -1 && getBalance(currentNode->right_) <= 0)
  285. leftRotate(currentNode);
  286. // Left Right Case
  287. if (currentNodeBalance > 1 && getBalance(currentNode->left_) < 0) {
  288. currentNode->left_ = leftRotate(currentNode->left_);
  289. rightRotate(currentNode);
  290. }
  291. // Right Left Case
  292. if (currentNodeBalance < -1 && getBalance(currentNode->right_) > 0) {
  293. currentNode->right_ = rightRotate(currentNode->right_);
  294. leftRotate(currentNode);
  295. }
  296. */
  297. return false;
  298. }
  299. int AVLCommands::DeleteMin() {
  300. return DeleteMin(root_);
  301. }
  302. void AVLCommands::DeleteLeaf(std::shared_ptr<BSTNode> currentNode) {
  303. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  304. if (parent == nullptr) {
  305. // Delete root
  306. root_ = nullptr;
  307. size_--; assert(size_ == 0);
  308. } else {
  309. if (parent->right_ == currentNode) {
  310. parent->right_ = nullptr;
  311. } else if (parent->left_ == currentNode) {
  312. parent->left_ = nullptr;
  313. } else {
  314. std::cerr << "BST::DeleteLeaf Error: inconsistent state\n";
  315. }
  316. size_--; assert(size_ >= 0);
  317. }
  318. }
  319. int AVLCommands::DeleteMin(std::shared_ptr<BSTNode> currentNode) {
  320. std::shared_ptr<BSTNode> lastNode = nullptr;
  321. while (currentNode != nullptr) {
  322. lastNode = currentNode;
  323. currentNode = currentNode->left_;
  324. }
  325. int result = lastNode->key_;
  326. std::shared_ptr<BSTNode> parent = lastNode->parent_.lock();
  327. if (parent == nullptr) {
  328. // lastNode is root
  329. if (lastNode->right_ != nullptr) {
  330. root_ = lastNode->right_;
  331. lastNode->right_->parent_.reset();
  332. } else {
  333. root_ = nullptr;
  334. }
  335. } else {
  336. // lastNode under the root
  337. if (lastNode->right_ != nullptr) {
  338. parent->left_ = lastNode->right_;
  339. lastNode->right_->parent_ = parent;
  340. } else {
  341. parent->left_ = nullptr;
  342. }
  343. }
  344. size_--; assert(size_ >= 0);
  345. return result;
  346. }
  347. size_t AVLCommands::size() const {
  348. return size_;
  349. }
  350. bool AVLCommands::empty() const {
  351. return size_ == 0;
  352. }
  353. bool AVLCommands::Find(int key) const {
  354. std::shared_ptr<BSTNode> currentNode = root_;
  355. while (currentNode != nullptr) {
  356. if (currentNode->key_ == key) {
  357. return true;
  358. }
  359. currentNode = (key < currentNode->key_) ?
  360. currentNode->left_ : currentNode->right_;
  361. }
  362. return false;
  363. }
  364. std::string AVLCommands::JSON() const {
  365. nlohmann::json result;
  366. std::queue< std::shared_ptr<BSTNode> > nodes;
  367. if (root_ != nullptr) {
  368. result["root"] = root_->key_;
  369. nodes.push(root_);
  370. while (!nodes.empty()) {
  371. auto v = nodes.front();
  372. nodes.pop();
  373. std::string key = std::to_string(v->key_);
  374. //std::string height = std::to_string(v->height_);
  375. //result[key]["height"] = height;
  376. result[key]["left"] = v->left_->key_;
  377. if (v->left_ != nullptr) {
  378. result[key]["left"] = v->left_->key_;
  379. nodes.push(v->left_);
  380. }
  381. if (v->right_ != nullptr) {
  382. result[key]["right"] = v->right_->key_;
  383. nodes.push(v->right_);
  384. }
  385. if (v->parent_.lock() != nullptr) {
  386. result[key]["parent"] = v->parent_.lock()->key_;
  387. } else {
  388. result[key]["root"] = true;
  389. }
  390. }
  391. }
  392. result["size"] = size_;
  393. return result.dump(2) + "\n";
  394. }