Binary Search Tree Minimum Difference 2023 (Required)
Time limit: 5000ms
Memory limit: 256mb
Description:
In this exercise, you are required to fulfill the following two tasks.
1. Construct a binary search tree(BST).
Initially, the BST is empty. Then given a sequence of distinct integers, you need to insert them into the BST one by one. Lecture notes show more details on insertion.
2. Perform a traversal of the tree and find the minimum difference between consecutive nodes.
The main function has been provided. You need to complete three functions.
Node* createNode(int data);
Node* insertNode(Node* root, int data);
int minDifference(Node* root);
Sample Input 1:
5
10 20 30 50 40
Sample Output 1:
Input the number of integers:
Input these integers:
Minimum difference:
10
Sample Input 2:
11
2 1 4 10 3 5 7 8 9 6 0
Sample Output 2:
Input the number of integers:
Input these integers:
Minimum difference:
1
Code Template:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for BST node
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Function to create a new node
Node* createNode(int data) {
/*
Fill in your code here...
*/
}
// Function to insert a node in the BST
Node* insertNode(Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
/*
Fill in your code here...
*/
return root;
}
int minDifference(Node* root) {
int min_diff = INT_MAX;
/*
Fill in your code here...
Calculate the minimum difference between any two nodes.
*/
return min_diff;
}
int main()
{
int n, key;
Node* root = NULL;
printf("Input the number of integers:\n");
scanf("%d",&n);
printf("Input these integers:\n");
for(int i=0; i<n; i++)
{
scanf("%d", &key);
root = insertNode(root, key);
}
// Find the minimum difference between any two different nodes
int min_diff = minDifference(root);
printf("Minimum difference:\n%d", min_diff);
return 0;
}
Submit