AVLCommands.cpp 11 KB

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