Skip to content

Instantly share code, notes, and snippets.

@pashu123
Created November 13, 2016 18:21
Show Gist options
  • Save pashu123/7d63b35b12ef4323fa1b4848a49de74b to your computer and use it in GitHub Desktop.
Save pashu123/7d63b35b12ef4323fa1b4848a49de74b to your computer and use it in GitHub Desktop.
Tree
// Binary Search Tree - Implemenation in C++
// Simple program to create a BST of integers and search an element in it
#include<iostream>
using namespace std;
//Definition of Node for Binary search tree
struct BstNode {
int data;
BstNode* left;
BstNode* right;
};
//Function to print the elements
void inorder(BstNode* root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
// Function to create a new Node in heap
BstNode* GetNewNode(int data) {
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// To insert data in BST, returns address of root node
BstNode* Insert(BstNode* root,int data) {
if(root == NULL) { // empty tree
root = GetNewNode(data);
}
// if data to be inserted is lesser, insert in left subtree.
else if(data <= root->data) {
root->left = Insert(root->left,data);
}
// else, insert in right subtree.
else {
root->right = Insert(root->right,data);
}
return root;
}
//To search an element in BST, returns true if element is found
bool Search(BstNode* root,int data) {
if(root == NULL) {
return false;
}
else if(root->data == data) {
return true;
}
else if(data <= root->data) {
return Search(root->left,data);
}
else {
return Search(root->right,data);
}
}
int main() {
BstNode* root = NULL; // Creating an empty tree
/*Code to test the logic*/
int n,p;
cout<<"Enter how many elements to be inserted";
cin>>n;
for(int i=0;i<n;i++)
{
cin>>p;
root=Insert(root,p);
}
// Ask user to enter a number.
int number;
cout<<"Enter number be searched\n";
cin>>number;
//If number is found, print "FOUND"
if(Search(root,number) == true) cout<<"Found\n";
else cout<<"Not Found\n";
inorder(root);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment