Cycle 03
Lab Cycle 3 — Linked List & Trees
Binary Search Tree Insertion
Problem Statement
Write a program to insert nodes into a binary search tree.
#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