From f8c2b788f1bbc172b797344a98e0f1dc51d7dea8 Mon Sep 17 00:00:00 2001 From: Momi Date: Fri, 29 Oct 2021 13:52:45 +0530 Subject: [PATCH] Added binary_search_tree_insertion --- binary_search_tree.cpp | 97 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 binary_search_tree.cpp diff --git a/binary_search_tree.cpp b/binary_search_tree.cpp new file mode 100644 index 0000000..66b75f7 --- /dev/null +++ b/binary_search_tree.cpp @@ -0,0 +1,97 @@ +#include +using namespace std; + +class BST +{ + int data; + BST *left, *right; + +public: + // Default constructor. + BST(); + + // Parameterized constructor. + BST(int); + + // Insert function. + BST* Insert(BST*, int); + + // Inorder traversal. + void Inorder(BST*); +}; + +// Default Constructor definition. +BST ::BST() + : data(0) + , left(NULL) + , right(NULL) +{ +} + +// Parameterized Constructor definition. +BST ::BST(int value) +{ + data = value; + left = right = NULL; +} + +// Insert function definition. +BST* BST ::Insert(BST* root, int value) +{ + if (!root) + { + // Insert the first node, if root is NULL. + return new BST(value); + } + + // Insert data. + if (value > root->data) + { + // Insert right node data, if the 'value' + // to be inserted is greater than 'root' node data. + + // Process right nodes. + root->right = Insert(root->right, value); + } + else + { + // Insert left node data, if the 'value' + // to be inserted is greater than 'root' node data. + + // Process left nodes. + root->left = Insert(root->left, value); + } + + // Return 'root' node, after insertion. + return root; +} + +// Inorder traversal function. +// This gives data in sorted order. +void BST ::Inorder(BST* root) +{ + if (!root) { + return; + } + Inorder(root->left); + cout << root->data << endl; + Inorder(root->right); +} + +// Driver code +int main() +{ + BST b, *root = NULL; + root = b.Insert(root, 50); + b.Insert(root, 30); + b.Insert(root, 20); + b.Insert(root, 40); + b.Insert(root, 70); + b.Insert(root, 60); + b.Insert(root, 80); + + b.Inorder(root); + return 0; +} + +