Here is the code of binary search tree
#include<stdio.h>
#include<conio.h>
#include"malloc.h"
struct node
{
int data;
struct node* left;
struct node* right;
};
int size(struct node* n)
{
if(n==NULL)
return 0;
else
return (size(n->left)+1+size(n->right));
}
int maxdepth(struct node* n)
{
int ldepth,rdepth;
if(n==NULL)
{
return 0;
}
else
{
ldepth=maxdepth(n->left);
rdepth=maxdepth(n->right);
if(ldepth>rdepth)
return (ldepth+1);
else
return (rdepth+1);
}
}
int lookup(struct node* node,int target)
{
if(node==NULL)
return 0;
else if(target==node->data)
return 1;
else if(target<node->data)
return(lookup(node->left,target));
else
return(lookup(node->right,target));
}
struct node* newnode(int data)
{
struct node* newnod=(struct node*)malloc(sizeof(struct node));
newnod->data=data;
newnod->left=NULL;
newnod->right=NULL;
return newnod;
}
struct node* insert(struct node* root,int target)
{
if(root==NULL)
return(newnode(target));
else if(target<=root->data)
root->left=insert(root->left,target);
else
root->right=insert(root->right,target);
return root;
}
void main()
{
int result,s,max;
struct node* newnode=NULL;
clrscr();
newnode=insert(newnode,2);
newnode=insert(newnode,3);
newnode=insert(newnode,4);
max=maxdepth(newnode);
printf("maxdepth %d\n",max);
s=size(newnode);
result=lookup(newnode,3);
printf("size %d\n",s);
printf("%d",result);
getch();
}
When I runs this program . I get maxdepth has 3.
If I change the maxdepth function as
int maxdepth(struct node* n)
{
int ldepth,rdepth;
if(n==NULL)
{
return 0;
}
else
{
ldepth=maxdepth(n->left);
rdepth=maxdepth(n->right);
if(ldepth>rdepth)
return (ldepth);
else
return (rdepth);
}
}
I get the maxdepth value as 0. what is the problem? I couldn’t not figure it out?
You are not counting the current node, so a
+1is needed.Without the
+1maxdepthalways will return0. Becauseldepthandrdepthwill always be0.An example of a tree with 3 nodes:
Now you call
maxdepth(A), this will do:ldepth = maxdepth(B); rdepth = maxdepth(C);, thenmaxDepth(B)will do:ldepth = maxdepth(null); rdepth = maxdepth(null); /* ldepth and rdepth are now 0 */, somaxDepth(B)will return as a result0. SimilarmaxDepth(C)will return0. You will do then:But both
ldepthandrdepthare0, sordepthwill be returned which is0. Finallymaxdepth(A)will return 0 as a result.That’s why
+1is needed.