Implementing Binary Search Tree (BST) - C++ Programming language

Implementing Binary Search Tree (BST) - C++ Programming language

Instructor-svgAl-Mamun Sarkar
Apr 16 , 2020

Implementing Binary Search Tree (BST) - C++ Programming language. The following c++ code shows how to implement Binary Search Tree (BST).

 

Code:

#include 
using namespace std;

struct BstNode {
    int data;
    BstNode* left;
    BstNode* right;
};

BstNode* GetNewNode (int data)
{
    BstNode* newNode = new BstNode();
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}



BstNode* Insert(BstNode* root, int data)
{
   if (root == NULL) {
        root = GetNewNode(data);
   } else if (data <= root->data) {
       root->left = Insert(root->left, data);
   } else {
       root->right = Insert(root->right, data);
   }

   return root;
}


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->left, data);

}


int main()
{
    BstNode* root = NULL;

    root = Insert(root, 15);
    root = Insert(root, 10);
    root = Insert(root, 20);
    root = Insert(root, 25);
    root = Insert(root, 8);
    root = Insert(root, 12);

    int number;
    cout << "Enter number be searched\n";
    cin >> number;
    if(Search(root, number) == true)
        cout << "Found\n";
    else
        cout << "Not Found\n";

    return 0;
}

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram