SoFunction
Updated on 2024-11-18

Two ways to implement the minimum depth of a binary tree in Python

Find the minimum depth of a given binary tree

The minimum depth is the number of nodes on the shortest path from the root node to the nearest leaf node

Note: leaf nodes have no subtrees

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its minimum depth = 2.

1: The algorithm traverses each layer of the binary tree, and once a node in a layer is found to be childless, it returns the depth of that layer, which is the minimum depth of the binary tree

def minDepth(self, root):
    """
    :type root: TreeNode
    :rtype: int
    """
    if not root:
      return 0
    curLevelNodeList = [root]
    minLen = 1
    while curLevelNodeList is not []:
      tempNodeList = []
      for node in curLevelNodeList:
        if not  and not :
          return minLen
        if  is not None:
          ()
        if  is not None:
          ()
      curLevelNodeList = tempNodeList
      minLen += 1
    return minLen

2: Solving this problem by recursion is slightly different from "maximum depth of a binary tree". The main difference lies in the treatment of the case "the node exists in only one subtree", in which case the path of the minimum depth must include the nodes in that subtree.

def minDepth(self, root):
    """
    :type root: TreeNode
    :rtype: int
    """
    if not root:
      return 0
    if not  and  is not None:
      return ()+1
    if  is not None and not :
      return ()+1
    left = ()+1
    right = ()+1
    return min(left,right)

Algorithm questions from:/problems/minimum-depth-of-binary-tree/description/

This is the whole content of this article.