minimum depth of a binary tree

#include <stdio.h>

typedef struct Node
{
    int data;
    struct Node *left, *right;
} Node;

typedef Node* Tree;

#define min(a, b)(a)<(b)?(a):(b)

int mindepth(Tree t)
{
    if(t == NULL || (t->left == NULL && t->right == NULL)) return 0;
    return min( 1 + mindepth(t->left), 1 +  mindepth(t->right) );
}
Advertisements

5 thoughts on “minimum depth of a binary tree

  1. if(t == NULL || t->left == NULL || t->right == NULL)This would be true even if you reach a node with one child, instead it should be true only if you reach a leaf node i.e. right = left = NULL.So, I think the correct code should be,if(t == NULL || (t->left == NULL && t->right == NULL))

  2. Nice post. I learn something totally new and challenging on websites I stumbleupon
    everyday. It will always be useful to read content from other writers and practice a little something from their web sites.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s