Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Binary Tree C Code : Insertion : Find Max & MIn

Tuesday, October 7, 2014

Binary Tree C Code : Insertion : Find Max & MIn

In computer science, a binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-based binary tree data structure where each node has a comparable key (and an associated value) and satisfies the restriction that the key in any node is larger than the keys in all nodes in that node's left subtree and smaller than the keys in all nodes in that node's right sub-tree.

Insertion begins as a search would begin; if the key is not equal to that of the root, we search the left or right subtrees as before. Eventually, we will reach an external node and add the new key-value pair  as its right or left child, depending on the node's key. In other words, we examine the root and recursively insert the new node to the left subtree if its key is less than that of the root, or the right subtree if its key is greater than or equal to the root. Self referential structure has been used to link the nodes starting from the root node. In the code below, maximum and minimum value in the BST has been also calculated.


#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void findMax(node *root);
void findMin(node *root);
void searchKey(node *,int key);

int main() {
   node  *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);  
      if( val == -1)
          break;
      insert(&root, val);
   }
 
   findMin(root);
   printf("\n");
 
   findMax(root);
   printf("\n");
 
   printf("\n Enter the value to be searched:");
   scanf("%d",&search);
   searchKey(root,search);
   printf("\n");
  
   return 0;
}
void searchKey(node *root,int search) {
    if (root == NULL) {
        printf("\n Element Not Found:");
        return;
        }
    if (root->key == search) {
        printf("\n Key found:");
        return;
        }
    root->key < search ? searchKey(root->right,search) : searchKey(root->left,search);
    }
  
void findMax(node *root) {
    while(root->right != NULL)
        root = root->right;
    printf("\n Maximum value is:%d",root->key);
    }
  
void findMin(node *root) {
    while(root->left != NULL)
        root = root->left;
    printf("\n Minimum value is:%d",root->key);
    }  
  
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }

No comments:

Post a Comment