Skip to content

Commit

Permalink
fix: remove memory leak from reverse_binary_tree.cpp (#2730)
Browse files Browse the repository at this point in the history
  • Loading branch information
vil02 authored Sep 13, 2024
1 parent 7828b8e commit b169269
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions operations_on_datastructures/reverse_binary_tree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ class BinaryTree {
return pivot;
}

BinaryTree(const BinaryTree&) = delete;
BinaryTree& operator=(const BinaryTree&) = delete;

public:
/**
* @brief Creates a BinaryTree with a root pointing to NULL.
Expand All @@ -100,6 +103,21 @@ class BinaryTree {
* @brief Creates a BinaryTree with a root with an initial value.
*/
explicit BinaryTree(int64_t data) { root = new Node(data); }

~BinaryTree() {
std::vector<Node*> nodes;
nodes.emplace_back(root);
while (!nodes.empty()) {
const auto cur_node = nodes.back();
nodes.pop_back();
if (cur_node) {
nodes.emplace_back(cur_node->left);
nodes.emplace_back(cur_node->right);
delete cur_node;
}
}
}

/**
* @brief Adds a new Node to the Binary Tree
*/
Expand Down

0 comments on commit b169269

Please sign in to comment.