From fc7a92f016ca1500db2987b7add0b03d5aad910d Mon Sep 17 00:00:00 2001 From: William Zhang Date: Fri, 1 Mar 2019 11:09:16 -0500 Subject: [PATCH] fix memory leak in printTree() and remove not working with == --- labs/lab05/code/inlab/BinarySearchTree.cpp | 8 +++++--- labs/lab05/code/postlab/AVLTree.cpp | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/labs/lab05/code/inlab/BinarySearchTree.cpp b/labs/lab05/code/inlab/BinarySearchTree.cpp index 00f964c96..2083455a6 100644 --- a/labs/lab05/code/inlab/BinarySearchTree.cpp +++ b/labs/lab05/code/inlab/BinarySearchTree.cpp @@ -41,7 +41,8 @@ BinaryNode* BinarySearchTree::remove(BinaryNode*& n, const string& x) { return NULL; } // first look for x - if (x == n->value) { + int cmp = n->value.compare(x); + if (cmp == 0) { // found // no children if (n->left == NULL && n->right == NULL) { @@ -68,7 +69,7 @@ BinaryNode* BinarySearchTree::remove(BinaryNode*& n, const string& x) { string sr = min(n->right); n->value = sr; n->right = remove(n->right, sr); - } else if (x < n->value) { + } else if (cmp < 0) { n->left = remove(n->left, x); } else { n->right = remove(n->right, x); @@ -119,6 +120,7 @@ void BinarySearchTree::printTree(BinaryNode* root, Trunk* prev, bool isLeft) { trunk->str = " |"; printTree(root->right, trunk, false); + delete trunk; } -void BinarySearchTree::printTree() { printTree(root, NULL, false); } \ No newline at end of file +void BinarySearchTree::printTree() { printTree(root, NULL, false); } diff --git a/labs/lab05/code/postlab/AVLTree.cpp b/labs/lab05/code/postlab/AVLTree.cpp index 7f67e7a08..76746bfa4 100644 --- a/labs/lab05/code/postlab/AVLTree.cpp +++ b/labs/lab05/code/postlab/AVLTree.cpp @@ -59,7 +59,8 @@ AVLNode* AVLTree::remove(AVLNode*& n, const string& x) { return NULL; } // first look for x - if (x == n->value) { + int cmp = n->value.compare(x); + if (cmp == 0) { // found // no children if (n->left == NULL && n->right == NULL) { @@ -86,7 +87,7 @@ AVLNode* AVLTree::remove(AVLNode*& n, const string& x) { string sr = min(n->right); n->value = sr; n->right = remove(n->right, sr); - } else if (x < n->value) { + } else if (cmp < 0) { n->left = remove(n->left, x); } else { n->right = remove(n->right, x); @@ -156,6 +157,7 @@ void AVLTree::printTree(AVLNode* root, Trunk* prev, bool isLeft) { trunk->str = " |"; printTree(root->right, trunk, false); + delete trunk; } -void AVLTree::printTree() { printTree(root, NULL, false); } \ No newline at end of file +void AVLTree::printTree() { printTree(root, NULL, false); }