【LeetCode 简单题】118-二叉树的最小深度

题目描述:给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

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

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.

解法1。递归,是DFS做法,注意有的测试用例是左子树为空,此时不能返回1(注意看题干要求),所以要额外加左右子树是否为空的判断。

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if not root.left:
            return self.minDepth(root.right)+1
        if not root.right:
            return self.minDepth(root.left)+1
        return min(self.minDepth(root.left), self.minDepth(root.right))+1

解法2。迭代,是BFS做法。

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        root.val = 1
        q = [root]
        while q:
            node = q.pop(0)
            if not node.left and not node.right:
            # 最后while循环返回的出口,就是叶子结点的值,记录下的是到此处的深度
            # 因为肯定是深度最浅的叶子节点先被遍历,所以此处返回的是最小深度
                return node.val    
            if node.left:
                node.left.val = node.val+1
                q.append(node.left)
            if node.right:
                node.right.val = node.val+1
                q.append(node.right)
        

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/85994297
今日推荐