The Idea
The idea is traverse through all node in Binary Tree. For every node, if it is a leaf node, return 1. If not a leaf node and the left subtree is NULL, recur for right subtree, and vice versa. If both left and right subtrees are not NULL, then take the minimum of those two depth while recur the function again.
For Node class:
class Node
{
int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
For Binary Tree class:
class BinaryTree
{
//Root of the Binary Tree
public Node root;
int minimumDepth()
{
return minimumDepth(root);
}
/* Function to calculate the minimum depth of the tree */
public int minimumDepth(Node root)
{
// Corner case. Should never be hit unless the code is
// called on root = NULL
if (root == null)
return 0;
// Base case : Leaf Node. This accounts for height = 1.
if (root.left == null && root.right == null)
return 1;
// If left subtree is NULL, recur for right subtree
if (root.left == null)
return minimumDepth(root.right) + 1;
// If right subtree is NULL, recur for right subtree
if (root.right == null)
return minimumDepth(root.left) + 1;
return Math.Min(minimumDepth(root.left), minimumDepth(root.right)) + 1;
}
}
The Main class:
class Program
{
static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
//tree.root.right.right = new Node(6);
Console.WriteLine("Min. Depth is " + tree.minimumDepth(tree.root));
}
}