Skip to content

ashu102/program8

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 

Repository files navigation

program8

Once Monk was watching a fight between an array and a tree, of being better. Tree got frustrated and converted that array into a Binary Search Tree by inserting the elements as nodes in BST, processing elements in the given order in the array. Now Monk wants to know the height of the created Binary Search Tree. Help Monk for the same. Note:

  1. In Binary Search Tree, the left sub-tree contains only nodes with values less than or equal to the parent node; the right sub-tree contains only nodes with values greater than the parent node.
  2. Binary Search Tree with one node, has height equal to 1.

#include<stdio.h>

#include<stdlib.h>

struct node{

int data;

struct node *leftptr;

struct node *rightptr; };

struct node *root=NULL;

struct node* add(struct node* root, int data);

int length(struct node* t) ;

int main(void)

{ int n,i,a;

scanf("%d",&n);

for(i=0;i<=n-1;i++)

{ scanf("%d",&a);

root=add(root,a);

} int r=length(root);

printf("%d",r);

return 0;

}

struct node* add(struct node* root, int data1)

{ if (root == NULL) //If the tree is empty, return a new,single node

{ root=(struct node *)malloc(sizeof(struct node));

root->data=data1;

root->leftptr=NULL;

root->rightptr=NULL;

return root;

} else { if (data1 <= root->data)

root->leftptr = add(root->leftptr, data1);

else root->rightptr = add(root->rightptr, data1);

return root; }

} int length(struct node* t) { if (t==NULL) { return 0; } else {

int lDepth = length(t->leftptr);

int rDepth = length(t->rightptr);

if (lDepth > rDepth) { return(lDepth+1); } else { return(rDepth+1); } } }

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published