Deleting in Binary Tree sulotion - c++

After a few questions and some nice answers and friendly helpers here. I got the sulotion to my porblem with the deleting in the binary tree, i got suggested that, i can not just delet the largest number in the tree cause its may not the last or it has childrens 1 ,2 or none, so i made the code down below, i used a lot commenting hope that can help you people help me. What i actually dont know now, is how do i call this RemoveLargest() function in my public and then later in main, even though i dont know if the code will run properly.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
template<class T>
class BinaryTree
{
struct Node
{
T data;
Node* lChildptr;
Node* rChildptr;
Node(T dataNew)
{
data = dataNew;
lChildptr = NULL;
rChildptr = NULL;
}
};
private:
Node* root;
void Insert(T newData, Node* &theRoot) //Insert elements into the tree start.
{
if(theRoot == NULL)
{
theRoot = new Node(newData);
return;
}
if(newData < theRoot->data)
Insert(newData, theRoot->lChildptr);
else
Insert(newData, theRoot->rChildptr);
} //end.
void PrintTree(Node* theRoot) //print me the tree /start
{
if(theRoot != NULL)
{
PrintTree(theRoot->lChildptr);
cout<< theRoot->data<<" \n";
PrintTree(theRoot->rChildptr);
}
} //end.
T Largest( Node* theRoot) // show me largest number /start.
{
if ( root == NULL )
{
cout<<"There is no tree";
return -1;
}
if (theRoot->rChildptr != NULL)
{
return Largest(theRoot->rChildptr);
}
T value = theRoot->data;
return value;
} //end.
void RemoveLargest(Node* theRoot) //remove the largest priority number from tree /start.
{
Node* current; //the current tree?
Node* parent; //the parent of the current node?
current=theRoot;
// 3 cases :
// 1. We're removing a leaf node
// 2. We're removing a node with a single child
// 3. we're removing a node with 2 children
//Node with single child.
if((current->lChildptr == NULL && current->rChildptr != NULL)||(current->lChildptr != NULL && current->rChildptr == NULL))
{
if(current->lChildptr == NULL && current->rChildptr != NULL)
{
if(parent->lChildptr==current)
{
parent->lChildptr = current->rChildptr;
delete current;
}
else
{
parent->rChildptr = current->rChildptr;
delete current;
}
}
else //left child ok, no right child
{
if(parent->lChildptr==current)
{
parent->lChildptr = current->lChildptr;
delete current;
}
else
{
parent->rChildptr = current->lChildptr;
delete current;
}
}
return;
}
//We found a leaf(a node with not a single child)
if(current->lChildptr == NULL && current->rChildptr == NULL)
{
if (parent->lChildptr == current)
parent->lChildptr = NULL;
else
parent->rChildptr = NULL;
delete current;
return;
}
//Node with 2 children
// replace node with smallest value in right subtree
if (current->lChildptr != NULL && current->rChildptr != NULL)
{
Node* checkr;
checkr = current->rChildptr;
if((checkr->lChildptr == NULL)&&(checkr->rChildptr == NULL))
{
current=checkr;
delete checkr;
current->rChildptr = NULL;
}
else //right child has children
{
//if the node's right child has a left child
//Move all the way down left to locate smallest element
if ((current->rChildptr)->lChildptr != NULL)
{
Node* lcurr;
Node* lcurrp;
lcurrp = current->rChildptr;
lcurr = (current->rChildptr)->lChildptr;
while(lcurr->lChildptr != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->lChildptr;
}
current->data = lcurr->data;
delete lcurr;
lcurrp->lChildptr = NULL;
}
else
{
Node* temp;
temp = current->rChildptr;
current->data = temp ->data;
current->rChildptr = temp->rChildptr;
delete temp;
}
}
return;
}
};
public:
BinaryTree()
{
root = NULL;
}
void AddItem(T newData)
{
Insert(newData, root);
}
void PrintTree()
{
PrintTree(root);
}
T Largest()
{
return Largest(root);
}
void RemoveLargest()
{
RemoveLargest();
}
};
int main()
{
BinaryTree<int> *myBT = new BinaryTree<int>();
myBT->AddItem(5);
myBT->AddItem(1);
myBT->AddItem(4);
myBT->AddItem(2);
myBT->AddItem(3);
//for(int i = 0; i < 10; i++) //randommal tolti fel/fill with random
//myBT->AddItem(rand() % 100);
cout << "BinaryTree:" << endl; //kilistazaa a fat/ list my tree
myBT->PrintTree();
cout << "Largest element: " << myBT->Largest() << endl; //visszaadja a legnagyobb elemet/shows the largest number
myBT->RemoveLargest(); //suposed to delet the largest number
myBT->PrintTree(); //shows list again
}
edited the code, now its running, its creating the tree, shows the largest, but after i call my remove function still crashing... =/

Like I said before, I think you're making things overly complicated. You have to think of what it means that your node is the largest one, in the context of a binary search tree and the relationship between the keys in its nodes.
If a node is the largest one in the tree it cannot possibly have a right child pointer, because the right child would have to have a larger key. And then, if you know that it has at most a left child, you just replace your node with its possibly null left child, and you're done.
T ExtractLargest(Node*& n){
if (!n)
return -1;
if (n->rChildptr)
return ExtractLargest(n->rChildptr);
T result = n->data;
Node *d = n;
n = n->lChildptr;
delete d;
return result;
}

Related

BST node deletion loop in C++

I'm building a function for deleting a node in a binary tree; since two of three cases are fairly simple (no children and 1 child) I've built another function to "re-arrange" the nodes beneath the one I'm trying to delete, in case it has two children.
I built the function so that it returns a pointer, which is the re-arranged subtree, but I've also tried making a function that just changes the tree itself, without returning a value, but both seem to create a loop where the tree changes: when I try to print the tree, it's stuck printing between the value I replace and it's left child, back and forth until eventually a segfault 11 pops up. I'm really lost as even the debugger isn't helping me understand where the issue is, can anyone tell me where to look? Thank you in advance for your kind attention and your time
Here is the tree I was thinking of before the deletion:1
And here it is after the deletion:2
'''
if (found the value) // value is head (recursive)
{
Node* to_delete = head;
...
head = subNode (head);
delete to_delete;
}
'''
Node* b_tree :: subNode (Node*&head)
{
Node*curr = head->right;
if (((!curr->right) && (!curr->left)) || (!curr->left)) // if it's a leaf or at least if the left pointer is NULL
{
curr->left = head->left;
head->left = NULL;
Node*to_return = curr;
return to_return;
}else // if there's a lower value...
{
while (curr->left != NULL) // find the lowest in the sub-tree
{
curr = curr->left;
}
if (!curr->right)
{
curr->right = head->right;
curr->left = head->left;
Node* to_return = curr;
curr = NULL;
return to_return;
} else {
Node* temp = curr->right;
curr->right = head->right;
curr->left = head->left;
Node*to_return = curr;
curr = temp;
return to_return;
}
}
};
''' Here's the whole code
'''
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Node
{
Node ();
Node (string, int);
string name;
int value;
Node* left;
Node* right;
};
Node :: Node ()
{
left = right = NULL;
}
Node :: Node (string nome, int valore)
{
this->name = nome;
this->value = valore;
this->left = NULL;
this->right = NULL;
};
class b_tree
{
private:
Node* head;
void insRic (Node*&, Node);
void stampaRic (Node*);
void deleteRic (Node*&, Node);
Node* subNode (Node*&);
public:
b_tree ();
void inserimento (Node);
void delete (Node);
void stampa ();
};
b_tree :: b_tree ()
{
this->head = NULL;
};
void b_tree :: inserimento (Node temp)
{
insRic(this->head, temp);
};
void b_tree :: insRic (Node*& head, Node temp)
{
if (head != NULL)
{
if (temp.value < head->value)
{
insRic(head->left, temp);
} else if (temp.value > head->value)
{
insRic(head->right, temp);
}
} else
{
head = new Node (temp.name, temp.value);
}
};
void b_tree :: stampa ()
{
stampaRic (this->head);
};
void b_tree :: stampaRic (Node* head)
{
if (head != NULL)
{
if (head->left != NULL)
{
stampaRic (head->left);
}
cout << "Nome: " << head->name << " | Valore: " << head->value << endl;
if (head->right != NULL)
{
stampaRic (head->right);
}
}
};
Node* b_tree :: subNode (Node*&head)
{
Node*curr = head->right;
if (((!curr->right) && (!curr->left)) || (!curr->left)) // if it's a leaf or at least if the leftious pointer is NULL
{
curr->left = head->left;
head->left = NULL;
Node*to_return = curr;
return to_return;
}else // if there's a lower value...
{
while (curr->left != NULL) // find the lowest in the sub-tree
{
curr = curr->left;
}
if (!curr->right)
{
curr->right = head->right;
curr->left = head->left;
Node* to_return = curr;
curr = NULL;
return to_return;
} else {
Node* temp = curr->right;
curr->right = head->right;
curr->left = head->left;
Node*to_return = curr;
curr = temp;
return to_return;
}
}
};
void b_tree :: delete (Node temp)
{
deleteRic (this->head, temp);
};
void b_tree :: deleteRic (Node*& head, Node temp)
{
if (head != NULL) // if head points ot something
{
if (head->value != temp.value) // if the node I'm trying to delete has a different name, jusr call it again until it finds it
{
if (temp.value < head->value)
{
eliminaRic (head->left, temp);
} else if (temp.value > head->value)
{
eliminaRic (head->right, temp);
}
} else // once I've found the value I'm trying to delete;
{
Node*to_delete = head;
if ((head->right == NULL) && (head->left == NULL)) // checking that the node is not a leaf
{
head = NULL;
delete to_delete;
} else if (head->left == NULL) // if leftious pointer is null
{
to_delete = head->right;
delete to_delete;
} else if (head->right == NULL) // if right pointer in null
{
head = head->left;
delete to_delete;
}
else if ((head->right != NULL) && (head->left != NULL)) // if neither pointer is null (2 children);
{
head = subNode (head);
delete to_delete;
}
}
}
}
int main ()
{
b_tree*albero = new b_tree ();
Node temp = Node ();
for (int i = 0; i < 7; i++)
{
cout << "Insert name and value; name: "; cin >> temp.name; cout << " value : "; cin >> temp.value; cout << endl;
albero->inserimento(temp);
}
albero->stampa();
cout << "Insert the value of the node you wish to delete: "; cin >> temp.value;
albero->delete(temp);
albero->stampa();
}
'''
Here are some issues:
The main problem is in the second half of subNode. The following line (that occurs twice) creates a cycle:
curr->next = head->next;
As curr is a descendant of head->next, this closes a cycle. This cycle is not broken by anything that follows.
curr = NULL or curr = temp is useless. It only sets a value of a variable and doesn't mutate the tree (which may be what you thought it did).
to_return should not be set to curr, but to head->next.
Not a problem, but the if condition at the top of subNode is equivalent to just !curr->prev.
Not a problem, but head->prev = NULL is not really needed, as head is going to be deleted anyway.
When these points are taken into account, some code repetition can be avoided, and the code can be reduced to the following:
Node* b_tree :: subNode (Node*&head)
{
Node* curr = head->next;
while (curr->prev != NULL)
{
curr = curr->prev;
}
curr->prev = head->prev;
return head-next;
};
Side note: this algorithm will more quickly increase the gravity with which the tree is unbalanced, as a whole subtree is moved at a lower place in the tree. This may even double the height of the tree with just one delete operation. I would therefor prefer the original, popular algorithm for deletion.

How do I access a pointer from within a nested class?

This class's purpose is to emulate the functions of a Binary Search Tree. In the below code, I am trying to adapt it from a struct and a bunch of functions, into a wrapper class, called BST. One thing I am not sure of however, is how to access 'root' from within the node struct. Root is currently declared within the BST class.
class bst
{
public:
struct Node
{
public:
int data;
struct Node *left;
struct Node *right;
Node* FindMin(Node* root)
{
while(root->left != NULL) root = root->left;
return root;
}
Node* Insert(Node *root,int data)
{
if(root == NULL) {
root = new Node();
root->data = data;
root->left = root->right = NULL;
//Update Height & Size
bstHeight = 0;
bstSize = 0;
}
else if(data <= root->data)
root->left = Insert(root->left,data);
else
root->right = Insert(root->right,data);
return root;
}
Node* Delete(struct Node *root, int data)
{
if(root == NULL) return root;
else if(data < root->data) root->left = Delete(root->left,data);
else if (data > root->data) root->right = Delete(root->right,data);
//Value found
else {
// Case 1: No child
if(root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
//Update Height & Size
bstHeight = 0;
bstSize = 0;
}
//Case 2: One child
else if(root->left == NULL)
{
struct Node *temp = root;
root = root->right;
delete temp;
//Update Height & Size
bstHeight = 0;
bstSize = 0;
}
else if(root->right == NULL)
{
struct Node *temp = root;
root = root->left;
delete temp;
//Update Height & Size
bstHeight = 0;
bstSize = 0;
}
// case 3: 2 children
else
{
struct Node *temp = FindMin(root->right);
root->data = temp->data;
root->right = Delete(root->right,temp->data);
//Update Height & Size
bstHeight = 0;
bstSize = 0;
}
}
return root;
}
//# of Nodes in tree
void size(Node *root)
{
//Check if end
if(root == NULL) return;
//Not end
else
{
bstSize = bstSize + 1;
size(root->left); //Visit left subtree
size(root->right); // Visit right subtree
}
}
void height(Node *root, int temp)
{
//Check if end
if(root == NULL)
{
if(temp > bstHeight)
{
bstHeight = temp;
}
return;
}
//Not end
else
{
temp = temp + 1;
height(root->left, temp); //Visit left subtree
height(root->right, temp); // Visit right subtree
}
}
//Function to visit nodes in Inorder
void show()
{
if(root == NULL) return;
show(root->left); //Visit left subtree
printf("%d ",root->data); //Print data
show(root->right); // Visit right subtree
}
void check(Node *root)
{
//End of a 'branch'
if(root == NULL) return;
int value = 0;
value = root->data;
//Checking left subtree
if(value < root->left->data)
{
//Tree is NOT valid
valid = 0;
}
//Checking right subtree
if(value > root->right->data)
{
//Tree is NOT valid
valid = 0;
}
check(root->left); //Visit left subtree
printf("%d ",root->data); //Print data
//check(root->right); // Visit right subtree
}
};
Node* root = NULL;
};
Specifically, in the show function. It's not as simple as putting it into Node with the rest of the functions, as root needs to be unique, and new Node is called at least once. Show will not compile in the current state, and I'm not sure where to proceed from here.
Though the comment says everything, let me give an additional hint:
When you want to keep your code as similar as possible to what you have now, try to add a constructor to the Node class that expects a pointer or reference (preferable) to the root and check, that each time you create a Node, you give the root to the constructor.
By the way, it might even be a better approach to look at some simple Node-based data structure implementations in C++, for example in the thread
Simple linked list in C++

AVL Tree Insertion Without Recursion C++

I am using the Following code to Implement the AVL Tree Insertion but its not display in proper order nor its updating height I also left some function because when insertion completed than i will be able to complete those fucntions
AVLNode.cpp
#include <iostream>
#include <string>
#include "AVLNode.h"
using namespace std;
AVLNode::AVLNode(string ss, string na){
ssn = ss;
name = na;
height = 0;
left = NULL;
right = NULL;
parent = NULL;
}
AVLNode.h
#include <iostream>
#include <string>
using namespace std;
struct AVLNode{
string ssn;
string name;
AVLNode *left;
AVLNode *right;
AVLNode *parent;
int height;
AVLNode(string ss, string na);
};
AVLTree.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include "AVLTree.h"
#include <iomanip>
#include <queue>
using namespace std;
AVLTree::AVLTree(){
root = NULL;
}
AVLTree::~AVLTree(){
}
AVLNode* AVLTree::getRoot(){
return root;
}
// search value ss in the AVL tree
bool AVLTree::find(string ss){
if (root == NULL) {
return false;
}
AVLNode* node = root;
while (node != NULL) {
if (ss.compare(node->ssn) == 0) {
return true;
}
if (ss.compare(node->ssn) < 0) {
node = node->left;
}
else{
node = node->right;
}
}
return false;
}
// return the height of the subtree rooted at node
// if subtree is empty, height is -1
// if subtree has one node, height is 0
int AVLTree::height(AVLNode* node){
if(node != NULL){
return node->height;
}
else{
return -1;
}
}
// return the balance factor of the node
int AVLTree::balanceFactor(AVLNode* node){
return height(node->left) - height(node->right);
}
// update the height of the node
// this should be done whenever the tree is modified
void AVLTree::updateHeight(AVLNode* node){
int hl = height(node->left);
int hr = height(node->right);
node->height = (hl > hr ? hl : hr) + 1;
}
// rotate right the subtree rooted at node
// return the new root of the subtree
AVLNode* AVLTree::rotateRight(AVLNode* node){
AVLNode* lp = node->left; // left child of node
if (node->parent != NULL) { // node is not root
if (node->parent->left == node) { // node is a left child
node->parent->left = lp;
}else{
node->parent->right = lp; // node is a right child
}
}
if (lp->right != NULL) { // pointer update
lp->right->parent = node;
}
lp->parent = node->parent;
node->left = lp->right;
lp->right = node;
node->parent = lp;
updateHeight(node); // after rotation, update height
updateHeight(lp); // after rotation, update height
if (node == root) {
root = lp;
}
return lp; // lp is the new root of the subtree
}
// rotate left the subtree rooted at node
// return the new root of the subtree
AVLNode* AVLTree::rotateLeft(AVLNode* node){
AVLNode* rp = node->right;
if (node->parent!=NULL) {
if (node->parent->left == node) {
node->parent->left = rp;
}else{
node->parent->right = rp;
}
}
if (rp->left != NULL) {
rp->left->parent = node;
}
rp->parent = node->parent;
node->right = rp->left;
rp->left = node;
node->parent = rp;
node->parent = rp;
updateHeight(node);
updateHeight(rp);
if (node == root) {
root = rp;
}
return rp;
}
// rebalance a tree rooted at node
// return the new root of the subtree
AVLNode* AVLTree::balance(AVLNode* node){
updateHeight(node);
if (balanceFactor(node) == 2) {
if (balanceFactor(node->left) < 0) {
node->left = rotateLeft(node->left); // for left right case
}
AVLNode* temp = rotateRight(node);
updateHeight(temp);
return temp;
}
if (balanceFactor(node) == -2) {
if (balanceFactor(node->right) > 0) {
node->right = rotateRight(node->right); // for right left case
}
AVLNode* temp2 = rotateLeft(node);
updateHeight(temp2);
return temp2;
}
return node;
}
// insert a new node with (ss, na) to the AVL tree
// if there exists ss value, return false
// otherwise, insert it, balance the tree, return true
bool AVLTree::insert(string ss, string na){
AVLNode *newNode=new AVLNode(ss,na);
AVLNode *Iterator;
if(root==NULL){
cout<<"Root Node Inserted"<<endl;
root=newNode;
} else {
Iterator = root;
int rootTempValue = atoi((Iterator->ssn).c_str());
int addTempValue = atoi((newNode->ssn).c_str());
if(rootTempValue <= addTempValue ){
// Right Portion of the tree
while(Iterator->right != NULL){
cout << "In the Right portion" <<endl;
int rootTempValue2 = atoi((Iterator->right->ssn).c_str());
int addTempValue2 = atoi((newNode->ssn).c_str()) ;
if(rootTempValue2 <= addTempValue2 )
Iterator = Iterator->right;
else
Iterator = Iterator->left;
//Iterator = Iterator->right;
}
Iterator->right = newNode ;
newNode->parent = Iterator ;
} else {
// Left Portion of the tree
while(Iterator->left != NULL){
//Iterator = Iterator->left;
int rootTempValue2 = atoi((Iterator->left->ssn).c_str());
int addTempValue2 = atoi((newNode->ssn).c_str()) ;
if(rootTempValue2 <= addTempValue2 )
Iterator = Iterator->right;
else
Iterator = Iterator->left;
}
newNode->parent = Iterator;
newNode->right = NULL ;
newNode->left = NULL;
Iterator->left = newNode ;
cout << "In the left portion : " <<Iterator->left->ssn<<endl;
}
}
balance(newNode);
updateHeight(newNode);
return true;
}
AVLNode* AVLTree::maxOfSubtree(AVLNode* node){
if (node == NULL) {
return NULL;
}
while (node->right != NULL) {
node = node->right;
}
return node;
}
// delete the node containing value ss
// if there is not such node, return false
// otherwise, delete the node, balance the tree, return true
bool AVLTree::deleteNode(string ss){
// please implement here
return true;
}
// internal function
// do not call it directly
void AVLTree::print(AVLNode* x, int indent){
if(x == NULL)
return;
if (x->right != NULL) {
print(x->right, indent+4);
}
if (indent != 0) {
cout << std::setw(indent) << ' ';
}
if(x->right != NULL){
cout << " /\n" << std::setw(indent) << ' ';
}
cout << x->ssn << endl;
if (x->left != NULL) {
cout << std::setw(indent) << ' ' <<" \\\n";
print(x->left, indent+4);
}
}
// print out the structure of the binary tree
// use it for debugging, I love this function
void AVLTree::print(){
int count = 0;
print(root, count);
}
// it does not level order traversal
// it prints out the number of node
// use it mainly for debugging
void AVLTree::levelOrder(){
// please implement it
}
main.cpp
#include <iostream>
#include "AVLTree.h"
int main(int argc, char** argv) {
AVLTree temp;
temp.insert("05", "a");
temp.insert("04", "b");
temp.insert("09", "c");
//temp.insert("03", "d");
//temp.insert("06", "d");
// temp.insert("07", "d");
//temp.insert("02", "d");
temp.print();
cout<<endl;
cout<<"The Height Of The Tree is :" << temp.height(temp.getRoot())<<endl;
cin.get();
return 0;
}
Your AVLTree has a complex class invariant and expressing it is generally a good idea for an efficient debug.
If you write a method like
bool
AVLTree::invariant() const {
if (root == NULL)
return true;
std::stack<AVLNode*> stack;
stack.push_back(root);
while (!stack.empty()) {
AVLNode* currentNode = stack.back();
int leftHeight = -1, rightHeight = -1;
if (currentNode->left) {
leftHeight = currentNode->left->height;
if (currentNode->left->parent != currentNode)
return false;
if (currentNode->left.height+1 != currentNode->height)
return false;
}
if (currentNode->right) {
rightHeight = currentNode->right->height;
if (currentNode->left->parent != currentNode)
return false;
if (currentNode->left.height+1 != currentNode->height)
return false;
}
if (leftHeigth > rightHeigth+1 || rightHeight > leftHeight+1)
return false;
if (currentNode->left)
stack.push_back(currentNode->left);
else {
do {
stack.pop_back();
AVLNode* parentNode = !stack.empty() ? stack.back() : NULL;
if (currentNode && parentNode->right != currentNode && parentNode->right) {
stack.push_back(parentNode->right);
break;
};
currentNode = parentNode;
} while (currentNode);
};
};
return true;
}
you can then debug your main function by adding into it the following code
assert(temp.invariant());
temp.insert("05", "a");
assert(temp.invariant());
temp.insert("04", "b");
assert(temp.invariant());
temp.insert("09", "c");
assert(temp.invariant());
As soon as you have identified the insertion that fails, you just have to break on the return false; in the invariant method that is executed. At this point you should be able to understand the origin of the bug.
Why not just use a std::stack? Recursion is basically just looping off of the call stack as it is.
if (!root)
root = new AVLNode(ss, na);
else
{
AVLNode *current = root;
AVLNode *previous = NULL;
std::stack<AVLNode*> rstack;
while (current != NULL)
{
previous = current;
//Use String Compare instead of cast
if (ss.compare(current->ssn) < 0) //If ss less than current
...
rstack.push(previous);
}
...
...
while (!rstack.empty())
{
rstack.top() = balance(rstack.top());
rstack.pop();
}
}

Implementation of removeNode for a Binary Search Tree

I'm trying to implement a removal algorithm discussed in a textbook for a binary search tree in a program, but the book is scant on details for some of the functions described so I've guessed at their meaning and implemented the functions it specified and some of my own. The problem I'm having is with the removeNode function on handling the 0-1-2 children cases.
In the book it specifies the following pseudocode for removeNode
removeNode(N: BinaryNode)
{
if(N is a leaf)
Remove N from the tree
else if (N has only one child C)
{
if(N was a left child of its parent P)
Make C the left child of P
else
Make C the right child of P
}
else //Node has two children
{
//Find S, the node that contains N's inorder successor
//Copy the item from node S into node N
//Remove S from the tree by using the previous
//technique for a leaf or a node with one child
}
In this function, how do you make C a child of P? given a single node with nothing to point back to the parent what can you do to figure out who the parent of the tree is? Usually you need a trailing node to keep track of that but due to the books 'final draft' I suspect that wasn't what they were implying.
'Final Draft'
removeNode(nodePtr: BinaryNodePointer): BinaryNodePointer
{
if(N is a leaf)
{
//Remove leaf from the tree
delete nodePtr
nodePtr = nullPtr
return nodePtr
}
else if (N has only one child C)
{
if(N was a left child of its parent P)
nodeToConnectPtr = nodePtr->getleftChildPtr() //<---I assume this means nodePtr->left
else
nodeToConnectPtr = nodePtr->getRightChildPtr() //<--nodePtr->right?
delete nodePtr
nodePtr = nullptr
return nodeToConnectPtr
}
else //Node has two children
{
//Find the inorder succesor of the entry in N: it is in the left subtree rooted
//at N's Child
tempPtr = removeLeftMosstNode(nodePtr->getRightChild(), newNodeValue)
nodePtr->setRightChildPtr(tempPtr) //<--nodePtr->right = tempPtr?
nodePtr->setItem(newNodeValue) // nodePtr->vendorData = newNodeValue?
return nodePtr
}
This is the implementation I came up with based off the aforementioned design. I know some parts are wrong but I wasn't sure what else I could do to fix them. Could anyone suggest a fix the child cases and any other problems I might have missed?
My Implementation
aBst::treeNode * aBst::removeNode(aBst::treeNode * nodePtr)
{
//This functions deletes a node and then returns the pointer to the child to take the place of deleted child
aVendor * tempVendorPtr;
treeNode * nodeToConnectPtr, *tempPtr;
//The node passed is the node that needs to be removed
if (nodePtr->right == NULL && nodePtr->left == NULL) //----No Child----
{
delete nodePtr;
nodePtr = NULL;
return nodePtr;
}
else if ((nodePtr->right != NULL) != (nodePtr->left != NULL))//----One Child----
{
if (nodePtr->left != NULL)//left child
{
nodeToConnectPtr = nodePtr->left; //Wrong
}
else if (nodePtr->right != NULL) //right child
{
nodeToConnectPtr = nodePtr->right; //Wrong
}
delete nodePtr;
nodePtr = NULL;
return nodeToConnectPtr;
}
else //-----Two Child-----
{
//find minimum value of right subtree, stores the pointer to the vendorData it carries through the parameter and calls removeNode
tempPtr = removeLeftMostNode(nodePtr->right, tempVendorPtr);
nodePtr->vendorData = tempVendorPtr;
nodePtr->right = tempPtr;
return nodePtr;
}
}
All functions
int aBst::countKids(aBst::treeNode * subTreePtr)
{
if (subTreePtr == NULL) //Empty Tree
{
return -1;
}
else if (subTreePtr->right == NULL && subTreePtr->left == NULL) //----No Child----
{
return 0;
}
else if ((subTreePtr->right != NULL) != (subTreePtr->left != NULL))//----One Child----
{
return 1;
}
else if ((subTreePtr->right != NULL) && (subTreePtr->left != NULL))//----Two Child----
{
return 2;
}
//Something unexpected occurred
return -1;
}
bool aBst::remove(char nameOfVendor[])
{
bool failControl = false;
removeValue(root, nameOfVendor, failControl);
return failControl;
}
aBst::treeNode * aBst::removeValue(aBst::treeNode * subTreePtr, char nameOfVendor[], bool& success)
{
//Note: the subTreePtr should be root in initial call
treeNode * tmpPtr;
char name[MAX_CHAR_LENGTH];
//Make sure passed success bit is false
success = false;
subTreePtr->vendorData->getName(name);
if (subTreePtr == NULL) //Empty Tree
{
success = false;
return NULL;
}
else if (strcmp(name, nameOfVendor) == 0) //Evaluates to true if there is a match
{
subTreePtr = removeNode(subTreePtr);
success = true;
return subTreePtr;
}
else if (strcmp(name, nameOfVendor) > 0) // Go left
{
//Protects algorithm from bad data crash
if (subTreePtr->left == NULL)
{
return subTreePtr;
}
tmpPtr = removeValue(subTreePtr->left, nameOfVendor, success);
subTreePtr->left = tmpPtr;
return subTreePtr;
}
else // Go Right
{
//Protects algorithm from bad data crash
if (subTreePtr->right == NULL)
{
return subTreePtr;
}
tmpPtr = removeValue(subTreePtr->right, nameOfVendor, success);
subTreePtr->right = tmpPtr;
return subTreePtr;
}
//For loop was broken and function returns false
return subTreePtr;
}
aBst::treeNode * aBst::removeNode(aBst::treeNode * nodePtr)
{
aVendor * tempVendorPtr;
treeNode * nodeToConnectPtr, *tempPtr;
//The node passed is the node that needs to be removed
if (nodePtr->right == NULL && nodePtr->left == NULL) //----No Child----
{
delete nodePtr;
nodePtr = NULL;
return nodePtr;
}
else if ((nodePtr->right != NULL) != (nodePtr->left != NULL))//----One Child----
{
if (nodePtr->left != NULL)//left child
{
nodeToConnectPtr = nodePtr->left;
}
else if (nodePtr->right != NULL) //right child
{
nodeToConnectPtr = nodePtr->right;
}
delete nodePtr;
cout << "called\n";
nodePtr = NULL;
return nodeToConnectPtr;
}
else //-----Two Child-----
{
//find minimum value of right subtree, stores the pointer to the vendorData it carries through the parameter and calls removeNode
tempPtr = removeLeftMostNode(nodePtr->right, tempVendorPtr);
nodePtr->vendorData = tempVendorPtr;
nodePtr->right = tempPtr;
cout << "\nleaving Two Child\n";
return nodePtr;
}
}
aBst::treeNode * aBst::removeLeftMostNode(aBst::treeNode * nodePtr, aVendor*& vendorDataRef)
{
if (nodePtr->left == NULL)
{
//Target acquired
vendorDataRef = nodePtr->vendorData;
return removeNode(nodePtr);
}
else
return removeLeftMostNode(nodePtr->left, vendorDataRef);
}
I think you have a similar problem as I do. What you're doing when there is only one child, is just setting the pointer to branch to the right or left respectively. But you need to replace the node with a node from that subtree. This can be done by searching for the minimum node in the left subtree and replacing the node you wanted to remove with this minimum node. Then you need to remove the node you just inserted to prevent node duplication. That's the theory anyway. I haven't managed to implement it correctly myself.
edit: I removed the link again. I saw that it is considered bad etiquette to ask something in an answer. Shame on me /o.

Removing a Node in a BST

I am having trouble getting my remove300 and removeNode300 function working correctly when I remove the root of the tree. (In my case 8). Everything works right(compiling wise), but when I call me inView function, which displays the numbers in the binary tree in ascending order, it takes that 8 out and just puts the highest number in 8's place.
For example:
I insert these numbers in this order, 8,4,12,2,6,10,14,20 and call me remove function to remove 8. I get this output 2,4,5,20,10,12,14. I want it to be 2,4,6,10,12,14,20.
If I can get some help on this on why this process isn't working please let me know. Also let me know if I have to add anything to this post inorder to help you.
Struct definition:
typedef float Element300;
struct TreeNode300;
typedef TreeNode300 * TreePtr300;
struct TreeNode300
{
Element300 element;
TreePtr300 left;
TreePtr300 right;
};
Remove Function:
void BST300::remove300(const Element300 element, TreePtr300 & root)
{
if(root == NULL)
{
cerr << "Error: Remove Failed!" << endl;
}
else if(element == root->element )
{
removeNode300(root);
}
else if(element < root->element)
{
remove300(element, root->left);
}
else
{
remove300(element, root->right);
}
return;
}
Remove Node function:
void BST300::removeNode300(TreePtr300 & root)
{
TreePtr300 tempPointer = NULL;
if(root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
}
else if(root->right == NULL)
{
tempPointer = root;
root = root->left;
tempPointer->left = NULL;
delete tempPointer;
}
else if(root->left == NULL)
{
tempPointer = root;
root = root->right;
tempPointer->right = NULL;
delete tempPointer;
}
else
{
findMaxNode300(root->right, tempPointer);
root->element = tempPointer->element;
delete tempPointer;
}
tempPointer = NULL;
return;
}
find Maximum value function:
void BST300::findMaxNode300(TreePtr300 & root, TreePtr300 & tempPointer)
{
if(root->right == NULL)
{
tempPointer = root;
root = root->left;
tempPointer->left = NULL;
}
else
{
findMaxNode300(root->right, tempPointer);
}
return;
}