0% found this document useful (0 votes)
39 views

Graph

implementation of graph

Uploaded by

comseries756
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Graph

implementation of graph

Uploaded by

comseries756
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Assignment 6: Tree

Code Implementation
Task 1
#include <stdio.h>
#include <stdlib.h>

// Structure for a tree node


struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to insert nodes into the binary tree
struct Node* insertLevelOrder(int arr[], struct Node* root, int i, int n) {
if (i < n) {
struct Node* temp = createNode(arr[i]);
root = temp;

// Insert left child


root->left = insertLevelOrder(arr, root->left, 2 * i + 1, n);

// Insert right child


root->right = insertLevelOrder(arr, root->right, 2 * i + 2, n);
}
return root;
}
// Pre-order traversal
void preOrder(struct Node* root) {
if (root == NULL)
return;

printf("%d ", root->data);


preOrder(root->left);
preOrder(root->right);
}
// In-order traversal
void inOrder(struct Node* root) {
if (root == NULL)
return;

inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
// Post-order traversal
void postOrder(struct Node* root) {
if (root == NULL)
return;

postOrder(root->left);
postOrder(root->right);
printf("%d ", root->data);
}
// Function to find the height of the binary tree
int findHeight(struct Node* node) {
if (node == NULL)
return 0;

int leftHeight = findHeight(node->left);


int rightHeight = findHeight(node->right);

return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;


}
// Function to count the number of leaf nodes
int countLeafNodes(struct Node* root) {
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;

return countLeafNodes(root->left) + countLeafNodes(root->right);


}

int main() {
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);

struct Node* root = insertLevelOrder(arr, root, 0, n);

printf("Pre-order Traversal: ");


preOrder(root);
printf("\n");

printf("In-order Traversal: ");


inOrder(root);
printf("\n");

printf("Post-order Traversal: ");


postOrder(root);
printf("\n");
printf("Height of the Binary Tree: %d\n", findHeight(root));
printf("Number of Leaf Nodes: %d\n", countLeafNodes(root));
return 0;
}
Task 2
#include <stdio.h>
#include <stdlib.h>

// Structure for a BST node


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

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Helper function to get the height of the tree


int getHeight(Node* root) {
if (root == NULL)
return 0;
else {
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
}

// Helper function to print nodes at the current level


void printCurrentLevel(Node* root, int level) {
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1) {
printCurrentLevel(root->left, level - 1);
printCurrentLevel(root->right, level - 1);
}
}

// Function to perform level-order traversal of the BST


void levelOrderTraversal(Node* root) {
if (root == NULL) return;
int height = getHeight(root);
for (int i = 1; i <= height; i++) {
printCurrentLevel(root, i);
printf("\n");
}
}

// Function to insert a new node into the BST


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

// Function to search for a value in the BST


Node* search(Node* root, int key) {
if (root == NULL || root->data == key)
return root;
if (key < root->data)
return search(root->left, key);
return search(root->right, key);
}

// Function to find the minimum value node in the BST


Node* findMin(Node* root) {
while (root->left != NULL) root = root->left;
return root;
}

// Function to delete a node from the BST


Node* deleteNode(Node* root, int key) {
if (root == NULL) return root;
// Traverse the tree to find the node to delete
if (key < root->data)
root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
// Node with only one child or no child
if (root->left == NULL) {
Node* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL) {
Node* temp = root->left;
free(root);
return temp;
}
// Node with two children: Get the inorder successor (smallest in the right subtree)
Node* temp = findMin(root->right);
// Copy the inorder successor's content to this node
root->data = temp->data;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->data);
}
return root;
}

// Function to find the Lowest Common Ancestor (LCA) of two nodes


Node* findLCA(Node* root, int n1, int n2) {
if (root == NULL) return NULL;
// If both n1 and n2 are smaller than root, then LCA lies in the left subtree
if (root->data > n1 && root->data > n2)
return findLCA(root->left, n1, n2);
// If both n1 and n2 are greater than root, then LCA lies in the right subtree
if (root->data < n1 && root->data < n2)
return findLCA(root->right, n1, n2);
return root;
}

// Main function to test the BST operations


int main() {
Node* root = NULL;
int choice, value, n1, n2;
while (1) {
printf("\nBST Operations Menu:\n");
printf("1. Insert a node\n");
printf("2. Search for a value\n");
printf("3. Delete a node\n");
printf("4. Find LCA of two nodes\n");
printf("5. Level Order Traversal\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &value);
root = insert(root, value);
break;
case 2:
printf("Enter the value to search: ");
scanf("%d", &value);
Node* found = search(root, value);
if (found)
printf("Value %d found in the BST.\n", value);
else
printf("Value %d not found in the BST.\n", value);
break;
case 3:
printf("Enter the value to delete: ");
scanf("%d", &value);
root = deleteNode(root, value);
printf("Node deleted if it existed.\n");
break;
case 4:
printf("Enter two values to find LCA: ");
scanf("%d %d", &n1, &n2);
Node* lca = findLCA(root, n1, n2);
if (lca)
printf("LCA of %d and %d is %d.\n", n1, n2, lca->data);
else
printf("LCA not found.\n");
break;
case 5:
printf("Level order traversal of the BST:\n");
levelOrderTraversal(root);
break;
case 6:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;}
Task 3
#include <stdio.h>

#include <stdlib.h>

#include <limits.h> // Add this line for INT_MIN and INT_MAX

// Structure for a binary tree node

typedef struct Node {

int data;

struct Node* left;

struct Node* right;

} Node;

// Function to create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;

newNode->left = newNode->right = NULL;

return newNode;

// 1. Function to check if the binary tree is balanced

// A utility function to find the height of the tree

int height(Node* node) {

if (node == NULL) return 0;

int leftHeight = height(node->left);

int rightHeight = height(node->right);


return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;

// Function to check if the tree is balanced

int isBalanced(Node* root) {

if (root == NULL) return 1; // An empty tree is balanced

int leftHeight = height(root->left);

int rightHeight = height(root->right);

// Check if the difference in height is more than 1

if (abs(leftHeight - rightHeight) > 1) return 0;

// Check if the left and right subtrees are balanced

return isBalanced(root->left) && isBalanced(root->right);

// 2. Function to check if the binary tree is a valid BST

int isBSTUtil(Node* root, int min, int max) {

if (root == NULL) return 1;

// If this node violates the min/max constraint, return false

if (root->data <= min || root->data >= max) return 0;

// Otherwise, check recursively for subtrees, updating the range

return isBSTUtil(root->left, min, root->data) &&

isBSTUtil(root->right, root->data, max);

// Wrapper function for checking if the tree is a BST

int isBST(Node* root) {

return isBSTUtil(root, INT_MIN, INT_MAX);

// 3. Function to find the diameter of the binary tree

// Utility function to calculate the diameter and height simultaneously

int diameterUtil(Node* root, int* height) {

if (root == NULL) {

*height = 0;
return 0;

int leftHeight = 0, rightHeight = 0;

// Recursively calculate the height of the left and right subtrees

int leftDiameter = diameterUtil(root->left, &leftHeight);

int rightDiameter = diameterUtil(root->right, &rightHeight);

// Calculate the current height

*height = (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;

// Calculate the diameter: max of (left diameter, right diameter, height of left + right + 1)

return (leftHeight + rightHeight + 1 > leftDiameter && leftHeight + rightHeight + 1 > rightDiameter)

? (leftHeight + rightHeight + 1) : (leftDiameter > rightDiameter ? leftDiameter : rightDiameter);

// Wrapper function to find the diameter

int diameter(Node* root) {

int height = 0;

return diameterUtil(root, &height);

// Main function to test the tree operations

int main() {

Node* root = NULL;

int choice, value;

// Creating a simple test tree

root = createNode(10);

root->left = createNode(5);

root->right = createNode(20);

root->left->left = createNode(3);

root->left->right = createNode(8);

root->right->right = createNode(25);

while (1) {

printf("\nBinary Tree Operations Menu:\n");

printf("1. Check if the tree is balanced\n");


printf("2. Check if the tree is a valid BST\n");

printf("3. Find the diameter of the tree\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

if (isBalanced(root))

printf("The tree is balanced.\n");

else

printf("The tree is not balanced.\n");

break;

case 2:

if (isBST(root))

printf("The tree is a valid BST.\n");

else

printf("The tree is not a valid BST.\n");

break;

case 3:

printf("The diameter of the tree is: %d\n", diameter(root));

break;

case 4:

exit(0);

default:

printf("Invalid choice! Please try again.\n");

return 0;

Sample and Significant Outputs


Task 1
Pre-order Traversal: 1 2 4 5 3 6 7
In-order Traversal: 4 2 5 1 6 3 7
Post-order Traversal: 4 5 2 6 7 3 1
Height of the Binary Tree: 3
Number of Leaf Nodes: 4
Task 2
BST Operations Menu:
1. Insert a node
2. Search for a value
3. Delete a node
4. Find LCA of two nodes
5. Level Order Traversal
6. Exit
Enter your choice: 1
Enter the value to insert: 12

BST Operations Menu:


1. Insert a node
2. Search for a value
3. Delete a node
4. Find LCA of two nodes
5. Level Order Traversal
6. Exit
Enter your choice: 1
Enter the value to insert: 23

BST Operations Menu:


1. Insert a node
2. Search for a value
3. Delete a node
4. Find LCA of two nodes
5. Level Order Traversal
6. Exit
Enter your choice: 5
Level order traversal of the BST:
12
23

BST Operations Menu:


1. Insert a node
2. Search for a value
3. Delete a node
4. Find LCA of two nodes
5. Level Order Traversal
6. Exit
Enter your choice:
Task 3
Binary Tree Operations Menu:
1. Check if the tree is balanced
2. Check if the tree is a valid BST
3. Find the diameter of the tree
4. Exit
Enter your choice: 1
The tree is balanced.
Binary Tree Operations Menu:
1. Check if the tree is balanced
2. Check if the tree is a valid BST
3. Find the diameter of the tree
4. Exit
Enter your choice: 2
The tree is a valid BST.

Binary Tree Operations Menu:


1. Check if the tree is balanced
2. Check if the tree is a valid BST
3. Find the diameter of the tree
4. Exit
Enter your choice: 3
The diameter of the tree is: 5

Binary Tree Operations Menu:


1. Check if the tree is balanced
2. Check if the tree is a valid BST
3. Find the diameter of the tree
4. Exit
Enter your choice:

You might also like