Pages

Friday, July 25, 2025

BST (Insertion + Inorder)

 #include <iostream>

using namespace std;


struct Node {

    int data;

    Node* left;

    Node* right;

    

    Node(int val) {

        data = val;

        left = right = NULL;

    }

};



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

    // Base Case

    if(root == NULL) {

        return new Node(value);

    }

    

    if(value < root->data) {

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

    } else if(value > root->data) {

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

    }

    

    return root;

    

}



void inorder(Node* root) {

    if(root == NULL) {

        return;

    }

    

    inorder(root->left);

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

    inorder(root->right);

}



int main() {

    Node* root = NULL;


    // Insert elements into BST

    root = insert(root, 50);

    insert(root, 30);

    insert(root, 60);

    

    cout << "Inorder Traversal OF BST: ";

    inorder(root);

    cout << endl;


    return 0;

}

No comments:

Post a Comment

Binary Search in a Sorted Array in C++

 #include <iostream> using namespace std; int binarySearch(int arr[], int key, int n) {     int si = 0;      int ei = n-1;          wh...