From 8fb5f133364c4d05abbeff442f92af84db304b6b Mon Sep 17 00:00:00 2001 From: TUNQRT Date: Tue, 25 Feb 2025 23:12:43 +0100 Subject: [PATCH] delete --- tree.cpp | 60 ++++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/tree.cpp b/tree.cpp index b160322..96453d2 100644 --- a/tree.cpp +++ b/tree.cpp @@ -3,27 +3,64 @@ #include #include +template +struct Node; + +template +using Node_ptr = std::unique_ptr>; + template struct Node{ T value; - std::unique_ptr> small; - std::unique_ptr> big; + Node_ptr small; + Node_ptr big; void dump(std::ofstream& ofs) const; }; template class Tree{ - std::unique_ptr> root; + Node_ptr root; + Node_ptr* find(T val); + Node_ptr* find_to_swap(Node_ptr* unwanted); + public: bool insert(T val); - void del(T val); - + bool del(T val); void print() const; }; +template +Node_ptr* Tree::find(T val){ + for(Node_ptr* n = &root; *n;){ + if(val == (*n)->value) return n; + else if(val < (*n)->value) n = &(*n)->small; + else n = &(*n)->big; + } + return nullptr; +} template -void del(T val); +Node_ptr* Tree::find_to_swap(Node_ptr* unwanted){ + if((*unwanted)->small) unwanted = &(*unwanted)->small; + else return nullptr; + while((*unwanted)->big) unwanted = &(*unwanted)->big; + return unwanted; +} + +template +bool Tree::del(T val){ + Node_ptr* unwanted = find(val); + if(!unwanted) return false; + Node_ptr* to_swap = find_to_swap(unwanted); + if(!to_swap){ + (*unwanted).reset((*unwanted)->big.release()); + } + else{ + std::swap((*unwanted)->value, (*to_swap)->value); + (*to_swap).reset((*to_swap)->small.release()); + } + return true; +} template bool Tree::insert(T val){ @@ -83,12 +120,15 @@ void Tree::print() const { int main(){ Tree t; - std::vector v = {3, 6, 8, 0, -1, 1, 4, 2}; + std::vector v = {3, 6, 8, -1, 7, 0, 9, 2, -11, 5}; for(auto i : v){ if(t.insert(i)) std::cout << "added " << i << "\n"; - else std::cout << "failed at " << i << "\n"; + else std::cout << "failed at adding " << i << "\n"; + t.print(); + } + for(auto i : v){ + if(t.del(i)) std::cout << "deleted " << i << "\n"; + else std::cout << "failed at deleting " << i << "\n"; t.print(); } - - } \ No newline at end of file