Find Minimum Depth of a Binary Tree

PROBLEM :

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from root node down to the nearest leaf node.

For example, minimum height of below Binary Tree is 2.
Example Tree



Note that the path must end on a leaf node. For example, minimum height of below Binary Tree is also 2.

          10
        /  
      5
   
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;---------------------------------------------*/

int height_tree(tree *) ;
void level_count(tree *,int ,int *) ;

int minimum_depth(tree *root)
{
int h,i,count,last ;
h=height_tree(root) ;
last=0 ;
for(i=1;i<=h;i++)
{
count=0 ;
level_count(root,i,&count) ;
if(count!=0)
return i ;
}
return h ;
}

int height_tree(tree *root)
{
if(root==NULL)
return 0 ;

int L_len,R_len ;

L_len=height_tree(root->left) ;
R_len=height_tree(root->right) ;

if(L_len>R_len)
return(1+L_len) ;
else
return(1+R_len) ;
}

void level_count(tree *root,int level,int *count)
{
if(root==NULL)
return ;

if(root->left==NULL&&root->right==NULL)
(*count)++ ;

else if(level!=1)
{
level_count(root->left,level-1,&(*count)) ;
level_count(root->right,level-1,&(*count)) ;
}
}

-----------------------------------------------------------------------------------------------------------------
ANOTHER IMPLEMENTATION
-----------------------------------------------------------------------------------------------------------------

int minimum_depth(tree *root)
{
if(!root)
return INT_MAX;
    if(!root->left && !root->right)
return 1;
    return min(minimum_depth(root->left), minimum_depth(root->right)) + 1;
}


---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )