zoukankan      html  css  js  c++  java
  • Leetcode 111. Minimum Depth of Binary Tree

    Description: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.

    Link: 111. Minimum Depth of Binary Tree

    EXamples:

    Example 1:
    Input: root = [3,9,20,null,null,15,7]
    Output: 2
    
    Example 2:
    Input: root = [2,null,3,null,4,null,5,null,6]
    Output: 5

    思路: 之前计算最深的路径时,是1+max(左子树的最深度,右子树的最深度),现在求最小深度,即最短路径的节点数,就用1+min(左子树的最小深度,右子树的最小深度)。但是看Example2, 如果没有左子树,最小深度不是1,而是右子树的最小深度5,所以要单独处理。

    class Solution(object):
        def minDepth(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root: return 0
            if not root.left:
                return 1 + self.minDepth(root.right)
            elif not root.right:
                return 1 + self.minDepth(root.left)
            else:
                return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

    日期: 2021-03-18

  • 相关阅读:
    1015
    1016
    1014
    1002
    1010
    1006
    动态规划1001
    动态规划1002
    使用EF框架调用带有输出参数(output)的存储过程
    工程地质相关知识
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14553512.html
Copyright © 2011-2022 走看看