Skip to content

Added binary_search_tree_insertion #215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions binary_search_tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#include <iostream>
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;
}