Fix binary tree
parent
fa18b01220
commit
a34b7e968b
|
@ -92,9 +92,11 @@ namespace blt {
|
||||||
nodeStack.push(current);
|
nodeStack.push(current);
|
||||||
current = current->left;
|
current = current->left;
|
||||||
}
|
}
|
||||||
current = nodeStack.front();
|
// take the parent node of the left most subtree
|
||||||
|
current = nodeStack.top();
|
||||||
nodeStack.pop();
|
nodeStack.pop();
|
||||||
nodes.push_back(current);
|
nodes.push_back(current);
|
||||||
|
// traverse its right tree
|
||||||
current = current->right;
|
current = current->right;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -111,18 +113,37 @@ namespace blt {
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] BST_node* search(const T& element) const {
|
[[nodiscard]] BST_node* search(const T& element) const {
|
||||||
search(nullptr, element);
|
return search(nullptr, element);
|
||||||
}
|
}
|
||||||
|
|
||||||
void remove(const T& element) {
|
void remove(const T& element) {
|
||||||
BST_node* parent = nullptr;
|
BST_node* parent = nullptr;
|
||||||
auto elementNode = search(parent, element);
|
BST_node* elementNode = search(parent, element);
|
||||||
// reconstruct subtree. More efficient way of doing this... TODO
|
|
||||||
std::vector<BST_node*> subNodes = inOrderTraverse(elementNode);
|
BST_node*& parentChildSide = parent->left;
|
||||||
for (auto* node : subNodes){
|
if (parent->right == elementNode)
|
||||||
if (node != elementNode)
|
parentChildSide = parent->right;
|
||||||
insert(parent, node->payload);
|
|
||||||
|
if (elementNode->left != nullptr && elementNode->right != nullptr){
|
||||||
|
parentChildSide = nullptr;
|
||||||
|
// reconstruct subtree. More efficient way of doing this... TODO
|
||||||
|
std::vector<BST_node*> 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<BST_node*> inOrderTraverse(){
|
||||||
|
return inOrderTraverse(m_root);
|
||||||
}
|
}
|
||||||
|
|
||||||
~node_binary_search_tree() {
|
~node_binary_search_tree() {
|
||||||
|
|
|
@ -61,7 +61,7 @@ namespace blt {
|
||||||
* Warning does not contain runtime error checking!
|
* Warning does not contain runtime error checking!
|
||||||
* @return the element at the "front" of the queue.
|
* @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];
|
return m_data[m_insertIndex - 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue