leetcode笔记--Minimum Depth of Binary Tree

Minimum Depth of Binary Tree
题目:难度(Easy)
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.
Tags:Tree, Depth-first Search ,Breadth-first Search

法1:DFS

分析:此题不能直接套用Maximum Depth of Binary Tree的方法直接使用depthMin = min(leftMinDepth, rightMinDepth)+1。因为像单支树这样的树,按题意它的深度应该是子树的深度+1,而不是0。

代码实现:

<span style="font-size:14px;"># 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):
    #DFS
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        if root.left and root.right:
            return min(self.minDepth(root.left), self.minDepth(root.right))+1
        elif root.left:
            return self.minDepth(root.left)+1
        else:
            return self.minDepth(root.right)+1</span>


法2:BFS

分析:找到的第一个叶子节点所在的高度就是该树的最小深度。

代码实现:

<span style="font-size:14px;"># 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 root is None:
            return 0
            
        from collections import deque
        queue = deque()
        queue.append(root)
        curNodesNumEachLevel = 1
        depthMin = 1
        while queue:
            frontElem = queue.popleft()
            curNodesNumEachLevel -= 1
            #注意:判断是否是叶子节点的条件语句必须放在depthMin += 1的前面
            #只有在某一层的全部节点考察完后深度才会加1,而在curNodesNumEachLevel=0之前,就可能先出现了叶子节点(在该层上)
            if frontElem.left is None and frontElem.right is None:#找到叶子节点
                break
            if frontElem.left:
                queue.append(frontElem.left)
            if frontElem.right:
                queue.append(frontElem.right)
            if curNodesNumEachLevel == 0:
                #上一层的节点都出队了,深度增加,到这一层
                depthMin += 1
                curNodesNumEachLevel = len(queue)
        return depthMin</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值