Skip to content

[111] Minimum Depth of Binary Tree

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/

  • algorithms
  • Easy (34.35%)
  • Source Code: 111.minimum-depth-of-binary-tree.py
  • Total Accepted: 285.7K
  • Total Submissions: 814K
  • Testcase Example: '[3,9,20,null,null,15,7]'

Given a binary tree, find its minimum depth.

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

Note: A leaf is a node with no children.

Example:

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

3

/
9 20 /
15 7

return its minimum depth = 2.

python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0

        # 不要算0就行了
        lvalue = self.minDepth(root.left)
        rvalue = self.minDepth(root.right)

        if lvalue and rvalue:
            return 1 + min(lvalue, rvalue)
        elif lvalue:
            return 1 + lvalue
        elif rvalue:
            return 1 + rvalue
        else:
            return 1

Last updated: