Binary Search Tree

youtube :

code:

#include<iostream>
using namespace std;
//Definition of Node for Binary search tree
struct BstNode
{
    int data;
    BstNode* left;
    BstNode* right;
};
//Function to create new Node in heap
BstNode* GetNewNode(int data)
{
    BstNode* newNode=new BstNode();
    newNode->data=data;
    newNode->left=newNode->right=NULL;
    return newNode;
}
//To search an element in BST return 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);
}
//TO insert data in BST, return 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 it 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;
}

int main()
{
    BstNode* root=NULL;//creating an empty tree
    /* Code to test the logic */
    root=Insert(root,15);
    root=Insert(root,10);
    root=Insert(root,20);
    root=Insert(root,25);
    root=Insert(root,8);
    root=Insert(root,12);
    //asking user to enter a number
    int number;
    cout<<"Enter number to be searched:\n";
    cin>>number;
    //If number is found, print "FOUND"
    if(Search(root,number)==true)
        cout<<"Found\n";
    else
        cout<<"Not Found\n";
    return 0;
}

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *