From b388ed60ded4ad045a5359518fa6faa20cf3cfbf Mon Sep 17 00:00:00 2001 From: Fuwn Date: Mon, 8 Jul 2024 08:09:42 -0700 Subject: feat: some --- bst.cc | 52 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/bst.cc b/bst.cc index e66756f..f5f4f07 100644 --- a/bst.cc +++ b/bst.cc @@ -108,8 +108,8 @@ public: return maximum; } - auto _remove(std::optional> bst, - T key) -> std::optional> { + static auto remove(std::optional> bst, + T key) -> std::optional> { // If the current BST being evaluated has no value, it could not possibly be // considering for child removal if (!bst.has_value()) { @@ -120,11 +120,11 @@ public: // the right-hand side, this additionally means that it is not the target // value if (bst.value()->_key < key) { - bst.value()->_right = this->_remove(bst.value()->_right, key); + bst.value()->_right = bst::remove(bst.value()->_right, key); return bst; } else if (bst.value()->_key > key) { - bst.value()->_left = this->_remove(bst.value()->_left, key); + bst.value()->_left = bst::remove(bst.value()->_left, key); return bst; } @@ -164,7 +164,41 @@ public: auto remove(T key) -> void { // `remove` is easier with recursion, so its wrapped - this->_remove(std::make_shared>(*this), key); + this->remove(std::make_shared>(*this), key); + } + + static auto print_from_largest_to_smallest( + std::optional> bst) -> void { + if (bst.has_value()) { + print_from_largest_to_smallest(bst.value()->_right); + + std::cout << bst.value()->_key << ' '; + + print_from_largest_to_smallest(bst.value()->_left); + } + } + + auto print_from_largest_to_smallest() -> void { + print_from_largest_to_smallest(std::make_shared>(*this)); + + std::cout << '\n'; + } + + static auto print_from_smallest_to_largest( + std::optional> bst) -> void { + if (bst.has_value()) { + print_from_smallest_to_largest(bst.value()->_left); + + std::cout << bst.value()->_key << ' '; + + print_from_smallest_to_largest(bst.value()->_right); + } + } + + auto print_from_smallest_to_largest() -> void { + print_from_smallest_to_largest(std::make_shared>(*this)); + + std::cout << '\n'; } }; @@ -176,6 +210,14 @@ auto main() -> int { bst.insert(5); bst.insert(1); + std::cout << "print largest to smallest: "; + + bst.print_from_largest_to_smallest(); + + std::cout << "print smallest to largest: "; + + bst.print_from_smallest_to_largest(); + std::cout << "size: " << bst.size() << '\n'; std::cout << "depth: " << bst.depth() << '\n'; std::cout << "minimum: " << bst.minimum() << '\n'; -- cgit v1.2.3