Tuesday, 3 November 2026

Write a Program Implementation of a BST Add

 Program to Add (Insert) a Node in BST

#include <iostream>

using namespace std;

struct Node {

    int data;

    Node *left, *right;

 //Stores the address of the left child and right child

};


Node* createNode(int value) //Creates a function to make a new node.

{

    Node* newNode = new Node();// Allocates memory for a new node

    newNode->data = value;//Stores the given value.

    newNode->left = NULL;//Initially, the left child is empty.

    newNode->right = NULL;//Initially, the right child is empty.

    return newNode;//Returns the address of the new node

}


Node* add(Node* root, int value) {

    if (root == NULL) {

        return createNode(value);

    }

  • Node* – The function returns the address of a node.

  • add – Function name.

  • Node* root – Receives the address of the root node.

  • int value – Receives the value that we want to insert.

      It checks whether the current node is empty or not.

If root == NULL, it means there is no node at that position.

So, we can insert a new node there.

    if (value < root->data) {

        root->left = add(root->left, value);

    }

    else if (value > root->data) {

        root->right = add(root->right, value);

    }


    return root;

}


void inorder(Node* root) {

    if (root != NULL) {

        inorder(root->left);

        cout << root->data << " ";

        inorder(root->right);

    }

}

It checks whether the current node exists or not.

  • If root is not NULL, execute the statements inside.

  • If root is NULL, stop that function call.


Inorder = Left → Root → Right 

int main() {

    Node* root = NULL;

   

  root = add(root, 50);

    root = add(root, 30);

    root = add(root, 70);

    root = add(root, 20);

    root = add(root, 40);

     cout << "BST after insertion: ";

    inorder(root);

    return 0;

}