If you have access to the most linked list, this is a piece of cake:
// Making liberal assumptions about the kind of naming / coding conventions that might have been used... ListNode *currentNode = rootNode; while(currentNode != NULL) { ListNode *nextNode = currentNode->Next; delete currentNode; currentNode = nextNode; } rootNode = NULL;
If this is a custom implementation of BST, then this may be the way it works internally if it is bound to a specific data structure.
If you do not have access to the internal parts, the response to Potatoswatter must be enabled. Assuming that the BST is configured as they assume, simply deleting the root of the node should automatically delete all allocated memory, as each parent in the tree will delete its children.
If you ask how to manually iterate over a binary tree, then you will perform the following recursive step:
void DeleteChildren(BSTNode *node) { // Recurse left down the tree... if(node->HasLeftChild()) DeleteChildren(node->GetLeftChild()); // Recurse right down the tree... if(node->HasRightChild()) DeleteChildren(node->GetRightChild()); // Clean up the data at this node. node->ClearData(); // assume deletes internal data // Free memory used by the node itself. delete node; } // Call this from external code. DeleteChildren(rootNode);
I hope I did not miss this moment and one of this helps.
source share