DSA Assignment 4
DSA Assignment 4
ASSIGNMENT 4
SALINI C P
M240869EC
EDT
1. Coding All students should have different trees Trees should have d=3 at least .
a) Take a binary tree and do tree traversals
b) coding
b)
CODE
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
int main() {
Node* root = new Node(23);
return 0;
}
OUTPUT
CODE
#include <iostream>
using namespace std;
// Node structure
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
// Insert a node
Node* insert(Node* root, int value) {
if (root == nullptr) return new Node(value);
if (value < root->data)
root->left = insert(root->left, value);
else
root->right = insert(root->right, value);
return root;
}
// Search a node
Node* search(Node* root, int value) {
if (root == nullptr || root->data == value)
return root;
if (value < root->data)
return search(root->left, value);
else
return search(root->right, value);
}
// Delete a node
Node* deleteNode(Node* root, int value) {
if (root == nullptr) return root;
// In-order traversal
void inOrder(Node* root) {
if (root != nullptr) {
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}
}
int main() {
Node* root = nullptr;
// Insert nodes
root = insert(root, 25);
root = insert(root, 20);
root = insert(root, 36);
root = insert(root, 10);
root = insert(root, 22);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 5);
root = insert(root, 12);
root = insert(root, 28);
root = insert(root, 38);
root = insert(root, 48);
// Search
int value = 22;
Node* found = search(root, value);
if (found)
cout << "Found " << value << endl;
else
cout << value << " not found" << endl;
// Delete
root = deleteNode(root, 36);
cout << "In-order after deletion: ";
inOrder(root);
cout << endl;
return 0;
}
OUTPUT