DSA Lab Assignment 3
DSA Lab Assignment 3
Ques 1:
Answer 1:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
};
node->val = value;
return node;
// If both n1 and n2 are smaller than root, LCA is in the left subtree
}
// If both n1 and n2 are greater than root, LCA is in the right subtree
// If one node is on the left and the other is on the right, root is the LCA
return root;
// Test cases
int main() {
root->left = newNode(3);
root->right = newNode(12);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->right->left = newNode(10);
root->right->right = newNode(14);
if (lca1 != NULL)
else
if (lca2 != NULL)
return 0;
Output:
Ques 2:
Answer 2:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
};
// Function to create a new node
node->val = value;
return node;
// Helper function for in-order traversal to find the k-th smallest element
return;
// Increment count, and check if the current node is the k-th smallest
(*count)++;
if (*count == k) {
*result = root->val;
return;
int count = 0;
int result = -1; // Default value if k is out of bounds
return result;
int main() {
root->left = newNode(3);
root->right = newNode(12);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->right->left = newNode(10);
root->right->right = newNode(14);
int k = 3;
k = 5;
return 0;
Output: