Find Minimum Depth of a Binary Tree | A Binary Tree node ; Iterative method to find minimum depth of Binary Tree ; Corner Case ; Create an empty queue for level order traversal ; Enqueue root and initialize depth as 1 ; Do level order traversal ; Remove the front queue item ; Get details of the removed item ; If this is the first leaf node seen so far then return its depth as answer ; If left subtree is not None , add it to queue ; if right subtree is not None , add it to queue ; Lets construct a binary tree shown in above diagram
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data 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 q = [ ] NEW_LINE q . append ( { ' node ' : root , ' depth ' : 1 } ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT queueItem = q . pop ( 0 ) NEW_LINE node = queueItem [ ' node ' ] NEW_LINE depth = queueItem [ ' depth ' ] NEW_LINE if node . left is None and node . right is None : NEW_LINE INDENT return depth NEW_LINE DEDENT if node . left is not None : NEW_LINE INDENT q . append ( { ' node ' : node . left , ' depth ' : depth + 1 } ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT q . append ( { ' node ' : node . right , ' depth ' : depth + 1 } ) NEW_LINE DEDENT DEDENT 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