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) );
}

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 comment