lc111. Minimum Depth of Binary Tree

  1. Minimum Depth of Binary Tree Easy

732

398

Favorite

Share 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.

思路:深度优先算法

代码: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') 正无穷

转载于:https://juejin.im/post/5d09a81ae51d4577555508e7

猜你喜欢

转载自blog.csdn.net/weixin_33735676/article/details/93173674