Minimum Depth of a Binary Tree

Given a binary tree, find its minimum depth.

Minimum Depth of a Binary Tree

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, the minimum height of the below Binary Tree is 2.

image

The idea is to traverse the given Binary Tree. For every node, check if it is a leaf node. If yes, then return 1. If not the leaf node then if the left subtree is NULL, then recur for the right subtree. And if the right subtree is NULL, then recur for the left subtree. If both left and right subtrees are not NULL, then take the minimum of two heights.

Below is the implementation of the above idea.

class Node:
    def __init__(self , key):
        self.data = key
        self.left = None
        self.right = None

def min_depth(node):
    if node is None:
        return 0
    if node.left is None and node.right is None:
        return 1
    return min(min_depth(node.left), min_depth(node.right)) + 1