码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 111. Minimum Depth of Binary Tree

时间:2021-03-18 14:37:13      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ret   nbsp   nod   strong   roo   rip   ini   example   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

Leetcode 111. Minimum Depth of Binary Tree

标签:ret   nbsp   nod   strong   roo   rip   ini   example   tree   

原文地址:https://www.cnblogs.com/wangyuxia/p/14553512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!