Friday, February 7, 2025

Implement Binary Search Tree (BST) to perform create and insert operations.

 1. Implement Binary Search Tree (BST) to perform create and insert operations.

/*Hint:- A Binary Search Tree has at most two child, the left child containing values less than it's parent and right child containing values greater than it's parent.*/



 1. Implement Binary Search Tree (BST) to perform create and insert operations.

#include <stdio.h>
 #include <stdlib.h>
struct Node
 int data;
 struct Node* left; 
struct Node* right; 
}; 
struct Node* createNode(int value) 
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); 
  if (newNode != NULL) 
  { 
    newNode->data = value; 
    newNode->left = NULL; 
    newNode->right = NULL; 
   }  
return newNode; 
}
struct Node* insertNode(struct Node* root, int value) 
   if (root == NULL) 
  { 
      return createNode(value); 
  } 
  if (value < root->data) 
  { 
      root->left = insertNode(root->left, value); 
  } 
  else if (value > root->data) 
  { 
     root->right = insertNode(root->right, value); 
   } 
return root; 
void displayTree(struct Node* root) 
{
    if (root != NULL) 
    { 
       printf("%d ", root->data); 
       displayTree(root->left); 
       displayTree(root->right); 
    } 
}
int main() 
struct Node* root = NULL; 
int nodeValue; 
char choice;
do {
    printf("Input a value in the binary tree: ");
    scanf("%d", &nodeValue);
    root = insertNode(root, nodeValue);
    printf("Want to insert another node? (y/n): ");
    scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
printf("\nBinary Tree Elements: ");
displayTree(root);
printf("\n");
return 0;
}


//Output

Input a value in the binary tree: 40

Want to insert another node? (y/n): y

Input a value in the binary tree: 35

Want to insert another node? (y/n): y

Input a value in the binary tree: 55

Want to insert another node? (y/n): y

Input a value in the binary tree: 5 
Want to insert another node? (y/n): n

Binary Tree Elements: 40 35 5 55




No comments:

Post a Comment

Implement Binary Search Tree (BST) to perform create and insert operations.

  1. Implement Binary Search Tree (BST) to perform create and insert operations. /*Hint:- A Binary Search Tree has at most two child, the l...