AVLCommands.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // height function partly based on code from
  2. // http://www.sanfoundry.com/cpp-program-implement-avl-trees/
  3. // balance function partly 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. //std::cout << "v, child: " << v->key_ << std::endl;
  46. //std::cout << "u, parent: " << u->key_ << std::endl;
  47. if (left_ == u || right_ == u) {
  48. std::cerr << "BSTNode::ReplaceChild Error: child passed as replacement\n";
  49. }
  50. if (left_ == v) {
  51. left_ = u;
  52. u->parent_ = v->parent_;
  53. } else if (right_ == v) {
  54. right_ = u;
  55. u->parent_ = v->parent_;
  56. } else {
  57. std::cerr << "BSTNode::ReplaceChild Error: non-child passed as argument\n";
  58. exit(EXIT_FAILURE);
  59. }
  60. }
  61. AVLCommands::AVLCommands() : root_(nullptr), size_(0) {} // add height here?
  62. int AVLCommands::max(int a, int b) {
  63. return (a > b)? a : b;
  64. }
  65. int AVLCommands::height(std::shared_ptr<BSTNode> currentNode) {
  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::cout << "balance called at key: " << currentNode->key_ << std::endl;
  93. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  94. if (currentNode != nullptr) {
  95. //std::cout << "Node's balance: " << currentNode->balance_ <<std::endl;
  96. if (currentNode->balance_ > 1) {
  97. // Left-Left rotation
  98. if (currentNode->left_->balance_ >= 0) {
  99. //std::cout << "Left-Left" << std::endl;
  100. rightRotate(currentNode);
  101. return;
  102. // Left-Right rotation
  103. } else if (currentNode->left_->balance_ < 0) {
  104. //std::cout << "Left-Right" << std::endl;
  105. currentNode->left_ = leftRotate(currentNode->left_);
  106. rightRotate(currentNode);
  107. return;
  108. }
  109. } else if (currentNode->balance_ < -1) {
  110. // Right-Right rotation
  111. if (currentNode->right_->balance_ <= 0) {
  112. //std::cout << "Right-Right" << std::endl;
  113. leftRotate(currentNode);
  114. return;
  115. // Right-Left rotation
  116. } else if (currentNode->right_->balance_ > 0) {
  117. //std::cout << "Right-Left" << std::endl;
  118. currentNode->right_ = rightRotate(currentNode->right_);
  119. leftRotate(currentNode);
  120. return;
  121. }
  122. }
  123. balance(parent);
  124. }
  125. return;
  126. }
  127. std::shared_ptr<BSTNode> AVLCommands::rightRotate(std::shared_ptr<BSTNode> currentNode){
  128. if (currentNode == nullptr) {
  129. std::cout << "Can't rotate on an empty node!" << std::endl;
  130. return currentNode;
  131. }
  132. //std::cout << "Right Rotate at node " << currentNode->key_ << std::endl;
  133. std::shared_ptr<BSTNode> newSubRoot = currentNode->left_;
  134. currentNode->left_ = newSubRoot->right_;
  135. if (newSubRoot->right_ != nullptr) {
  136. newSubRoot->right_->parent_ = currentNode;
  137. }
  138. newSubRoot->right_ = currentNode;
  139. std::shared_ptr<BSTNode> oldParent = currentNode->parent_.lock();
  140. currentNode->parent_ = newSubRoot;
  141. if (oldParent == nullptr) {
  142. root_ = newSubRoot;
  143. newSubRoot->parent_.reset();
  144. } else {
  145. if (oldParent->right_== currentNode) {
  146. oldParent->right_ = newSubRoot;
  147. }else{
  148. oldParent->left_ = newSubRoot;
  149. }
  150. newSubRoot->parent_ = oldParent;
  151. }
  152. // Update heights and balances for the whole tree
  153. height(root_);
  154. // Return new root
  155. return newSubRoot;
  156. }
  157. // Takes the root of the tree to be left rotated and rotates it to provide new root
  158. std::shared_ptr<BSTNode> AVLCommands::leftRotate(std::shared_ptr<BSTNode> currentNode){
  159. if (currentNode == nullptr) {
  160. std::cout << "Can't rotate on an empty node!" << std::endl;
  161. return currentNode;
  162. }
  163. //std::cout << "Left Rotate at node " << currentNode->key_ << std::endl;
  164. std::shared_ptr<BSTNode> newSubRoot = currentNode->right_;
  165. currentNode->right_ = newSubRoot->left_;
  166. if (newSubRoot->left_ != nullptr) {
  167. newSubRoot->left_->parent_ = currentNode;
  168. }
  169. newSubRoot->left_ = currentNode;
  170. std::shared_ptr<BSTNode> oldParent = currentNode->parent_.lock();
  171. currentNode->parent_ = newSubRoot;
  172. if (oldParent == nullptr) {
  173. root_ = newSubRoot;
  174. newSubRoot->parent_.reset();
  175. } else {
  176. if (oldParent->right_== currentNode) {
  177. oldParent->right_ = newSubRoot;
  178. }else{
  179. oldParent->left_ = newSubRoot;
  180. }
  181. newSubRoot->parent_ = oldParent;
  182. }
  183. // Update heights and balances of the whole tree
  184. height(root_);
  185. // Return new root
  186. return newSubRoot;
  187. }
  188. // Basic tree printing for testing purposes
  189. void AVLCommands::printTree(){
  190. printTree(root_);
  191. }
  192. void AVLCommands::printTree(std::shared_ptr<BSTNode> currentNode){
  193. if (root_ == nullptr) {
  194. std::cout << "tree is empty" << std::endl;
  195. return;
  196. } else {
  197. std::cout << "key: " << currentNode->key_ << std::endl;
  198. std::cout << "height: " << currentNode->height_ << std::endl;
  199. std::cout << "balance: " << currentNode->balance_ << std::endl;
  200. if (currentNode->parent_.lock() != nullptr) {
  201. std::cout << "parent: " << currentNode->parent_.lock()->key_ << std::endl;
  202. }
  203. if (currentNode->left_ != nullptr) {
  204. std::cout << "left" << std::endl;
  205. printTree(currentNode->left_);
  206. }
  207. if (currentNode->right_ != nullptr) {
  208. std::cout << "right" << std::endl;
  209. printTree(currentNode->right_);
  210. }
  211. }
  212. }
  213. void AVLCommands::Insert(int key) {
  214. //std::cout << "Inserting new key: " << key << std::endl;
  215. // BST insertion
  216. if (root_ == nullptr) {
  217. root_ = std::make_shared<BSTNode>(key);
  218. size_++;
  219. return;
  220. }
  221. std::shared_ptr<BSTNode> currentNode = root_, lastNode = nullptr;
  222. while (currentNode != nullptr) {
  223. lastNode = currentNode;
  224. currentNode = (key < currentNode->key_) ?
  225. currentNode->left_ : currentNode->right_;
  226. }
  227. if (key < lastNode->key_) {
  228. lastNode->left_ = std::make_shared<BSTNode>(key, lastNode);
  229. size_++;
  230. } else if (key > lastNode->key_) {
  231. lastNode->right_ = std::make_shared<BSTNode>(key, lastNode);
  232. size_++;
  233. }
  234. // update height and balance of the tree
  235. height(root_);
  236. balance(lastNode->parent_.lock());
  237. }
  238. bool AVLCommands::Delete(int key) {
  239. //std::cout << "Deleting key: " << key << std::endl;
  240. // base BST delete
  241. std::shared_ptr<BSTNode> currentNode = root_;
  242. std::shared_ptr<BSTNode> parent = nullptr;
  243. while (currentNode != nullptr) {
  244. if (currentNode->key_ == key) {
  245. if (currentNode->IsLeaf()) {
  246. DeleteLeaf(currentNode);
  247. } else if (currentNode->left_ == nullptr && currentNode->right_ != nullptr) {
  248. if (currentNode->parent_.lock() != nullptr) {
  249. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  250. parent->ReplaceChild(currentNode, currentNode->right_);
  251. } else { // if at the root
  252. root_ = currentNode->right_;
  253. currentNode = currentNode->right_;
  254. currentNode->parent_.reset();
  255. //std::cout << "Current node: " << currentNode->key_ << std::endl;
  256. //std::cout << "Right of current node: ";
  257. //std::cout << currentNode->right_->key_ << std::endl;
  258. //root_->ReplaceChild(currentNode->right_, currentNode);
  259. }
  260. size_--; assert(size_ >= 0);
  261. } else if (currentNode->right_ == nullptr && currentNode->left_ != nullptr) {
  262. if (currentNode->parent_.lock() != nullptr) {
  263. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  264. parent->ReplaceChild(currentNode, currentNode->left_);
  265. } else { // if at the root
  266. root_ = currentNode->left_;
  267. currentNode = currentNode->left_;
  268. currentNode->parent_.reset();
  269. //std::cout << "Current node: " << currentNode->key_ << std::endl;
  270. //std::cout << "Left of current node: ";
  271. //std::cout << currentNode->left_->key_ << std::endl;
  272. //root_->ReplaceChild(currentNode->left_, currentNode);
  273. }
  274. size_--; assert(size_ >= 0);
  275. } else {
  276. currentNode->key_ = DeleteMin(currentNode->right_);
  277. }
  278. }
  279. parent = currentNode->parent_.lock();
  280. currentNode = (key < currentNode->key_) ?
  281. currentNode->left_ : currentNode->right_;
  282. }
  283. // update height and balance of the tree
  284. height(root_);
  285. balance(parent);
  286. return false;
  287. }
  288. int AVLCommands::DeleteMin() {
  289. int deletedKey = DeleteMin(root_);
  290. // update the heights and balances of the whole tree
  291. height(root_);
  292. // find the smallest node after deletion
  293. std::shared_ptr<BSTNode> smallestNode = root_;
  294. std::shared_ptr<BSTNode> lastNode = nullptr;
  295. while (smallestNode != nullptr) {
  296. lastNode = smallestNode;
  297. smallestNode = smallestNode->left_;
  298. }
  299. // balance the tree
  300. balance(lastNode);
  301. return deletedKey;
  302. }
  303. void AVLCommands::DeleteLeaf(std::shared_ptr<BSTNode> currentNode) {
  304. std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
  305. if (parent == nullptr) {
  306. // Delete root
  307. root_ = nullptr;
  308. size_--; assert(size_ == 0);
  309. } else {
  310. if (parent->right_ == currentNode) {
  311. parent->right_ = nullptr;
  312. } else if (parent->left_ == currentNode) {
  313. parent->left_ = nullptr;
  314. } else {
  315. std::cerr << "BST::DeleteLeaf Error: inconsistent state\n";
  316. }
  317. size_--; assert(size_ >= 0);
  318. }
  319. }
  320. int AVLCommands::DeleteMin(std::shared_ptr<BSTNode> currentNode) {
  321. std::shared_ptr<BSTNode> lastNode = nullptr;
  322. while (currentNode != nullptr) {
  323. lastNode = currentNode;
  324. currentNode = currentNode->left_;
  325. }
  326. int result = lastNode->key_;
  327. std::shared_ptr<BSTNode> parent = lastNode->parent_.lock();
  328. if (parent == nullptr) {
  329. // lastNode is root
  330. if (lastNode->right_ != nullptr) {
  331. root_ = lastNode->right_;
  332. lastNode->right_->parent_.reset();
  333. } else {
  334. root_ = nullptr;
  335. }
  336. } else {
  337. // lastNode under the root
  338. if (lastNode->right_ != nullptr) {
  339. if (parent->left_ == lastNode){
  340. parent->left_ = lastNode->right_;
  341. lastNode->right_->parent_ = parent;
  342. } else {
  343. parent->right_ = lastNode->right_;
  344. lastNode->right_->parent_ = parent;
  345. }
  346. } else {
  347. if (parent->left_ == lastNode){
  348. parent->left_ = nullptr;
  349. } else {
  350. parent->right_ = nullptr;
  351. }
  352. }
  353. }
  354. size_--; assert(size_ >= 0);
  355. return result;
  356. }
  357. size_t AVLCommands::size() const {
  358. return size_;
  359. }
  360. bool AVLCommands::empty() const {
  361. return size_ == 0;
  362. }
  363. bool AVLCommands::Find(int key) const {
  364. std::shared_ptr<BSTNode> currentNode = root_;
  365. while (currentNode != nullptr) {
  366. if (currentNode->key_ == key) {
  367. return true;
  368. }
  369. currentNode = (key < currentNode->key_) ?
  370. currentNode->left_ : currentNode->right_;
  371. }
  372. return false;
  373. }
  374. std::string AVLCommands::JSON() const {
  375. nlohmann::json result;
  376. std::queue< std::shared_ptr<BSTNode> > nodes;
  377. if (root_ != nullptr) {
  378. result["height"] = root_->height_;
  379. result["root"] = root_->key_;
  380. nodes.push(root_);
  381. while (!nodes.empty()) {
  382. auto v = nodes.front();
  383. nodes.pop();
  384. std::string key = std::to_string(v->key_);
  385. std::string balance = std::to_string(v->balance_);
  386. std::string height = std::to_string(v->height_);
  387. result[key]["balance factor"] = balance;
  388. result[key]["height"] = height;
  389. if (v->left_ != nullptr) {
  390. result[key]["left"] = v->left_->key_;
  391. nodes.push(v->left_);
  392. }
  393. if (v->right_ != nullptr) {
  394. result[key]["right"] = v->right_->key_;
  395. nodes.push(v->right_);
  396. }
  397. if (v->parent_.lock() != nullptr) {
  398. result[key]["parent"] = v->parent_.lock()->key_;
  399. } else {
  400. result[key]["root"] = true;
  401. }
  402. }
  403. }
  404. result["size"] = size_;
  405. //std::cout << result << std::endl;
  406. return result.dump(2) + "\n";
  407. }