summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSanto Cariotti <sancn@live.com>2017-11-01 16:38:47 +0100
committerSanto Cariotti <sancn@live.com>2017-11-01 16:38:47 +0100
commit74148d4942ada0b0e1a7a00d10e4c68ff1c6bcfd (patch)
tree4034d893f3dd01751f4582789d7dc10e148bbaa4
parent673f60aef1b46f436b9364ace8a9a0a97d9d0620 (diff)
added binary search tree
-rw-r--r--cpp/bst.cc105
1 files changed, 105 insertions, 0 deletions
diff --git a/cpp/bst.cc b/cpp/bst.cc
new file mode 100644
index 0000000..bc9efaf
--- /dev/null
+++ b/cpp/bst.cc
@@ -0,0 +1,105 @@
+#include <iostream>
+
+using namespace std;
+
+struct Node {
+ int data;
+ Node *right, *left;
+ Node(int _data, Node *r = nullptr, Node* l = nullptr) : data(_data), right(r), left(l) {}
+};
+
+class BST {
+private:
+ Node *root;
+
+ void insert(Node* root, int data) {
+ if(root->data > data) {
+ if(!root->left) {
+ root->left = new Node(data);
+ } else {
+ insert(root->left, data);
+ }
+ } else {
+ if(!root->right) {
+ root->right = new Node(data);
+ } else {
+ insert(root->right, data);
+ }
+ }
+ }
+
+ Node* min(Node *root) {
+ while(root->left != nullptr) root = root->left;
+ return root;
+ }
+
+ Node* remove(Node* root, int data) {
+ if(root->data > data) root->left = remove(root->left, data);
+ else if(root->data < data) root->right = remove(root->right, data);
+ else {
+ if(root->right == nullptr && root->left == nullptr) {
+ delete root;
+ root = nullptr;
+ } else if(root->right == nullptr) {
+ Node* tmp = root->left;
+ delete root;
+ return tmp;
+ } else if(root->left == nullptr) {
+ Node* tmp = root->right;
+ delete root;
+ return tmp;
+ }
+
+ Node* tmp = min(root->right);
+ root->data = tmp->data;
+ root->right = remove(root->right, tmp->data);
+ }
+
+ return root;
+ }
+ void printBST(Node* root) {
+ if(!root) return;
+
+ printBST(root->left);
+ cout << root->data << ' ';
+ printBST(root->right);
+ }
+
+public:
+ void add(int data) {
+ if(root) {
+ this->insert(root, data);
+ } else {
+ root = new Node(data);
+ }
+
+ }
+
+ void rem(int data) {
+ if(root) {
+ this->remove(root, data);
+ } else return;
+ }
+
+ void print() {
+ printBST(this->root);
+ }
+};
+
+int main() {
+ BST* bst = new BST();
+
+ for(int i = 0; i < 9; i++) {
+ int zz;
+ std::cin >> zz;
+ bst->add(zz);
+ }
+ int zz;
+ std::cin >> zz;
+ bst->rem(zz);
+ bst->print();
+
+ delete bst;
+
+ return 0;
+}