Find Minimum Depth of a Binary Tree | Tree node ; 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 acoounts for height = 1 ; If left subtree is Null , recur for right subtree ; If right subtree is Null , recur for left subtree ; Let us construct the Tree shown in the above figure
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minDepth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT return 1 NEW_LINE DEDENT if root . left is None : NEW_LINE INDENT return minDepth ( root . right ) + 1 NEW_LINE DEDENT if root . right is None : NEW_LINE INDENT return minDepth ( root . left ) + 1 NEW_LINE DEDENT return min ( minDepth ( root . left ) , minDepth ( root . right ) ) + 1 NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print minDepth ( root ) NEW_LINE