Question 03 of 05

Binary Search Tree Insertion

Write a program to insert nodes into a binary search tree.

C++
#include <iostream>
using namespace std;

struct Node { int data; Node* left, *right; };

Node* insert(Node* root, int val) {
    if (root == NULL) {
        Node* newNode = new Node();
        newNode->data = val;
        newNode->left = newNode->right = NULL;
        return newNode;
    }
    if (val < root->data) root->left = insert(root->left, val);
    else root->right = insert(root->right, val);
    return root;
}

void inorder(Node* root) {
    if (root == NULL) return;
    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}

int main() {
    Node* root = NULL;
    root = insert(root, 50);
    insert(root, 30); insert(root, 70);
    inorder(root);
    return 0;
}
Question 3 of 5