【LintCode 简单】155. 二叉树的最小深度

1.问题描述:

给定一个二叉树,找出其最小深度。

二叉树的最小深度为根节点到最近叶子节点的最短路径上的节点数量。

 

2.样例:

样例 1:

输入: {}
输出: 0
样例 2:

输入:  {1,#,2,3}
输出: 3    
解释:
    1
     \ 
      2
     /
    3    
它将被序列化为 {1,#,2,3}
样例 3:

输入:  {1,2,3,#,#,4,5}
输出: 2    
解释: 
      1
     / \ 
    2   3
       / \
      4   5  
它将被序列化为 {1,2,3,#,#,4,5}

3.代码:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param root: The root of binary tree
    @return: An integer
    """

    def minDepth(self, root):
        # # write your code here
        # Method 1
        # MAX_DEPTH = 100000
        # count = 1
        # if root is None:
        #     return 0
        # if root.left is None and root.right is None:
        #     return 1
        # left_depth = MAX_DEPTH  if self.minDepth(root.left)==0 else self.minDepth(root.left)
        # right_depth = MAX_DEPTH if self.minDepth(root.right)==0 else self.minDepth(root.right)
        # if left_depth > right_depth:
        #     return right_depth + 1
        # else:
        #     return left_depth+ 1

        # Method 2
        if not root:
            return 0
        left_height = self.minDepth(root.left)
        right_height = self.minDepth(root.right)
        # 当前节点左子树或者右子树为空的情况下,至少有一个为0
        if not left_height or not right_height:
            return left_height + right_height + 1
        # 左右子树都不为空的情况
        else:
            return min(left_height, right_height) + 1

 方法1会出现超时的情况,是因为递归次数太多了!

可以根据方法1的思路进行改写,就可以成功通过测试,修改如下:     

        left_depth = self.minDepth(root.left)
        right_depth = self.minDepth(root.right)
        left_depth = MAX_DEPTH if left_depth==0 else left_depth
        right_depth = MAX_DEPTH if right_depth==0 else right_depth

方法2非常巧妙和简洁,归结为两种情况,左右子树有空的时候和子树都非空。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值