/** * creates a new BSTNode, Inserts it into the tree, and returns true * if the integer is already in the tree, does not Insert, and returns false */ bool BSTree::Insert(int contents, BSTNode*& root) { BSTNode* newNode = new BSTNode(contents); if (root == NULL) { root = newNode; size_ += 1; return true; } else if (newNode->contents() < root->contents()) { // if (root->left_child() == NULL) // { // root->set_left_child(newNode); // size_ += 1; // } // else Insert(contents, root->left_child()); } else if (newNode->contents() > root->contents()) { Insert(contents, root->right_child()); }else return false; }
/* * traverses the tree and removes the node containing the target * integer if present and returns true * return false if target integer is not in tree (or the tree is empty) */ bool BSTree::Remove(int content, BSTNode*& node) { if(node == NULL) { return false; } else { if(node->contents() == content && size_ == 1) //checking if root needs to be removed { delete node; node = NULL; size_ = 0; return true; } else if(content < node->contents()) //if less than node traverse to the left { Remove(content, node->left_child()); } else if(content > node->contents()) //if greater than node traverse to the right { Remove(content, node->right_child()); } else //if the node is equal to content { if(node->left_child() == NULL && node->right_child() == NULL) //if the node to remove has no left/right child { delete node; node = NULL; } else if(node->left_child() == NULL) //node to be removed has a right subtree { BSTNode* temp = node; node = node->right_child(); delete temp; } else if(node->right_child() == NULL) //node to be removed has a left subtree { BSTNode* temp = node; node = node->left_child(); delete temp; } else if(root_->contents() == node->contents()) { BSTNode* temp = new BSTNode(FindMin(node->left_child())); node->set_contents(temp->contents()); delete temp; node->left_child() = NULL; } else { BSTNode* temp = new BSTNode(FindMin(node->right_child())); node->set_contents(temp->contents()); delete temp; } size_--; return true; } } }
#include "catch.hpp" // For NULL #include <cstddef> #include "bs_tree.h" // To test for correct header guards #include "bst_node.h" #include "bst_node.h" #include "bs_tree.h" TEST_CASE("Default Constructor for BSTNode") { const BSTNode const_node; BSTNode node; BSTNode* p_node = &node; SECTION("Contents const Accessor") { CHECK(const_node.contents() == 0); } SECTION("Contents Accessor (Editable)") { node.contents() = 10; CHECK(node.contents() == 10); } SECTION("Left Child const Accessor") { CHECK(const_node.left_child() == NULL); } SECTION("Left Child Accessor (Editable)") { node.left_child() = &node; CHECK(node.left_child() == p_node); }