diff --git a/others/iterative_tree_traversals.cpp b/others/iterative_tree_traversals.cpp index 0f9713b0451..11fa1814688 100644 --- a/others/iterative_tree_traversals.cpp +++ b/others/iterative_tree_traversals.cpp @@ -180,6 +180,25 @@ std::vector BinaryTree::inOrderIterative(Node *root) { } return result; } +void deleteAll(Node *root) { + if (root) { + std::stack stack; + stack.push(root); + + while (!stack.empty()) { + const Node *current = stack.top(); + stack.pop(); + + if (current->right) { + stack.push(current->right); + } + if (current->left) { + stack.push(current->left); + } + delete current; + } + } +} } // namespace iterative_tree_traversals } // namespace others @@ -396,5 +415,7 @@ int main() { test6(binaryTree, root); // run inorder-iterative test on negative values std::cout << "\nIn-order test on-negative value Passed!" << std::endl; + deleteAll(root); + return 0; }