From 6dbfe789e8f92d4519599151bf56ea70ecfb178b Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Fri, 10 Nov 2017 08:28:47 +0100 Subject: fixed delete node --- cpp/bst.cc | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/cpp/bst.cc b/cpp/bst.cc index bc9efaf..7b0889b 100644 --- a/cpp/bst.cc +++ b/cpp/bst.cc @@ -34,25 +34,25 @@ private: } Node* remove(Node* root, int data) { - if(root->data > data) root->left = remove(root->left, data); + if(root == nullptr) return root; + else if(root->data > data) root->left = remove(root->left, data); else if(root->data < data) root->right = remove(root->right, data); else { + Node* tmp = root; if(root->right == nullptr && root->left == nullptr) { delete root; root = nullptr; } else if(root->right == nullptr) { - Node* tmp = root->left; - delete root; - return tmp; + root = root->left; + delete tmp; } else if(root->left == nullptr) { - Node* tmp = root->right; - delete root; - return tmp; + root = root->right; + delete tmp; + } else { + tmp = min(root->right); + root->data = tmp->data; + root->right = remove(root->right, tmp->data); } - - Node* tmp = min(root->right); - root->data = tmp->data; - root->right = remove(root->right, tmp->data); } return root; @@ -88,8 +88,8 @@ public: int main() { BST* bst = new BST(); - - for(int i = 0; i < 9; i++) { + int n; cin >> n; + for(int i = 0; i < n; i++) { int zz; std::cin >> zz; bst->add(zz); -- cgit v1.2.3-18-g5258