leetcode_111 二叉树的最小深度

835 阅读1分钟

要求

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

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

示例 1:

image.png

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

代码详解

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if root:
            if root.left and root.right:
                return 1 + min(self.minDepth(root.left),self.minDepth(root.right))
            elif root.left:
                return 1 + self.minDepth(root.left)
            elif root.right:
                return 1 + self.minDepth(root.right)
            else:
                return 1 

        else:
            return 0

另一思路

  • 更像深度遍历,在遍历的时候,不断的将根节点上的深度,加入到一个列表中,最后输出列表的最小值,就是最小的深度
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
        
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0

        self.depth_list = list()
        self.findAllDepth(root,0)
        return min(self.depth_list)
    
    def findAllDepth(self,root,depth):
        if not root.left and not root.right:
            depth += 1
            self.depth_list.append(depth)
            return
        
        if root.left:
            self.findAllDepth(root.left,depth + 1)
        
        if root.right:
            self.findAllDepth(root.right,depth + 1)
        return 

image.png

解题思路:我们使用递归的方式将我们的最小的深度转化成表达式的形式,当左右节点都存在的时候我们的取二者中的最小值,当只有左节点的时候或者只有右节点,我们直接加上节点的深度,都没有,这一层的深度是1,直接返回即可