Find Minimum Depth of a Binary Tree | C # implementation to find minimum depth of a given Binary tree ; Class containing left and right child of current node and key value ; Root of the Binary Tree ; Function to calculate the minimum depth of the tree ; Corner case . Should never be hit unless the code is called on root = NULL ; Base case : Leaf Node . This accounts for height = 1. ; If left subtree is NULL , recur for right subtree ; If right subtree is NULL , recur for left subtree ; Driver program to test above functions ; Let us construct the Tree shown in the above figure
using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public class BinaryTree { public Node root ; public virtual int minimumDepth ( ) { return minimumDepth ( root ) ; } public virtual int minimumDepth ( Node root ) { if ( root == null ) { return 0 ; } if ( root . left == null && root . right == null ) { return 1 ; } if ( root . left == null ) { return minimumDepth ( root . right ) + 1 ; } if ( root . right == null ) { return minimumDepth ( root . left ) + 1 ; } return Math . Min ( minimumDepth ( root . left ) , minimumDepth ( root . right ) ) + 1 ; } public 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 ) ; Console . WriteLine ( " The ▁ minimum ▁ depth ▁ of ▁ binary ▁ tree ▁ is ▁ : ▁ " + tree . minimumDepth ( ) ) ; } }