lc111. Minimum Depth of Binary Tree

  1. Minimum Depth of Binary Tree Easy

732node

398python

Favorite算法

Share Given a binary tree, find its minimum depth.bash

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.ui

Note: A leaf is a node with no children.spa

Example:rest

Given binary tree [3,9,20,null,null,15,7],code

3
複製代碼

/
9 20 /
15 7 return its minimum depth = 2.ip

思路:深度優先算法string

代碼:python3

# 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
        self.deep=float('inf')
        def dfs(root,level):
            if not root:return
            if not root.left and not root.right:
                self.deep=min(level,self.deep)
            else:
                dfs(root.left,level+1)
                dfs(root.right,level+1)
        dfs(root,1)
        return self.deep
複製代碼

tips: float('inf') 正無窮

相關文章
相關標籤/搜索