111. Minimum Depth of Binary Tree(二叉树最小深度)

2,344次阅读
没有评论

共计 740 个字符,预计需要花费 2 分钟才能阅读完成。

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.

解法:

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

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        def depth(node):
            if not node:
                return 0
            left=depth(node.left)
            right=depth(node.right)
            if left==0 or right==0:
                return left+right+1
            else:
                return min(left,right)+1
        return depth(root)

解释:

当左右子节点深度其中一个为0的时候,那么此时的深度由另外一边的深度+1来代替

if left==0 or right==0: return left+right+1

这个写法兼容两种情况,毕竟任何一个变量为0的时候就是相当于另外一个节点的深度+1

除此之外的情况就是当两个节点的深度都不为0的时候那么就是二者的最小值+1

正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-03-29发表,共计740字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码