diff --git a/include/blt/std/binary_tree.h b/include/blt/std/binary_tree.h index 7021c3e..db41e70 100644 --- a/include/blt/std/binary_tree.h +++ b/include/blt/std/binary_tree.h @@ -92,9 +92,11 @@ namespace blt { nodeStack.push(current); current = current->left; } - current = nodeStack.front(); + // take the parent node of the left most subtree + current = nodeStack.top(); nodeStack.pop(); nodes.push_back(current); + // traverse its right tree current = current->right; } @@ -111,18 +113,37 @@ namespace blt { } [[nodiscard]] BST_node* search(const T& element) const { - search(nullptr, element); + return search(nullptr, element); } void remove(const T& element) { BST_node* parent = nullptr; - auto elementNode = search(parent, element); - // reconstruct subtree. More efficient way of doing this... TODO - std::vector subNodes = inOrderTraverse(elementNode); - for (auto* node : subNodes){ - if (node != elementNode) - insert(parent, node->payload); + BST_node* elementNode = search(parent, element); + + BST_node*& parentChildSide = parent->left; + if (parent->right == elementNode) + parentChildSide = parent->right; + + if (elementNode->left != nullptr && elementNode->right != nullptr){ + parentChildSide = nullptr; + // reconstruct subtree. More efficient way of doing this... TODO + std::vector subNodes = inOrderTraverse(elementNode); + for (auto* node : subNodes){ + // insert will create a new node, we must delete old one to prevent memory leaks + if (node != elementNode) { + insert(parent, node->payload); + delete(node); + } + } + + } else { + parentChildSide = elementNode->left != nullptr ? elementNode->left : elementNode->right; } + delete(elementNode); + } + + std::vector inOrderTraverse(){ + return inOrderTraverse(m_root); } ~node_binary_search_tree() { diff --git a/include/blt/std/queue.h b/include/blt/std/queue.h index e747a1a..b295d59 100644 --- a/include/blt/std/queue.h +++ b/include/blt/std/queue.h @@ -61,7 +61,7 @@ namespace blt { * Warning does not contain runtime error checking! * @return the element at the "front" of the queue. */ - [[nodiscard]] const T& front() const { + [[nodiscard]] const T& top() const { return m_data[m_insertIndex - 1]; }