Question: I have a C++ question about deleting binary search tree. I am trying to delete the whole binary search tree ( every node in the

I have a C++ question about deleting binary search tree. I am trying to delete the whole binary search tree ( every node in the tree), which one of these functions do you think will work better?

private: struct Node { string value; Node* left; Node* right; }; Node* root; public: BST() { root = NULL; } ~BST() { delete root->left; delete root->right; } 
\\ or should i use the following: 
void destroyTree (Node*& tree) { while (tree != NULL) { tree = tree->left; delete tree; } while (tree != NULL) { tree = tree->right; delete tree; } delete tree; } 

.....................................................................

Can you also please check and see if my insert function is correct? I am trying to insert string nodes into binary search tree without using any recrusion.

Node* GetNewNode(string data){ Node* newNode = new Node(); newNode->value=data; newNode->left = newNode->right = NULL; return root; }

void insert(string word) { Node* current= root; if(current == NULL) { root = GetNewNode(word); } else while(current != NULL){ if(current->value.compare(word)<0) current=current->left; else current=current->right; } }

 
 
 
 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!