【LeetCode】111. Minimum Depth of Binary Tree

32 篇文章 0 订阅
32 篇文章 0 订阅

两种解法:

(1)深度优先遍历,与maximum depth of binary tree类似,时间复杂度O(n),递归函数栈结构空间复杂度O(logn),但需要考虑两种情况:

    i. 节点返回时必须为叶子节点,返回深度应该为1。

    ii. 为了满足i.实现时要返回非空子树的最小深度。

(2)广度优先遍历,优势在于,深度优先遍历会遍历全部子树,这在树非常不平衡时效率比较低。可以采用广度优先遍历来克服这一问题。时间复杂度O(n),最差情况的空间复杂度O(n)

Python源码:

Runtime: 28 ms, faster than 90.02% of Python online submissions for Minimum Depth of Binary Tree.

Memory Usage: 14.5 MB, less than 94.87% of Python online submissions for Minimum Depth of Binary Tree.

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

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        depth = 0
        found_leaf = False
        cur_nodes = [root]
        while not found_leaf:
            next_nodes = []
            while cur_nodes:
                if cur_nodes[-1].left != None:
                    next_nodes.append(cur_nodes[-1].left)
                if cur_nodes[-1].right != None:
                    next_nodes.append(cur_nodes[-1].right)
                if cur_nodes[-1].left == None and cur_nodes[-1].right == None:
                    found_leaf = True
                    break
                cur_nodes.pop()
            depth += 1
            cur_nodes = next_nodes
        return depth
        

我的心路:

    类似maximum depth of binary tree,依然采用递归法,把max函数改为min函数,但minimum depth需要多考虑的一个问题是,只有叶子节点可以返回深度,而maximum是无需考虑这一点的。所以要事先排除非叶子节点的返回。时间复杂度O(n),递归函数栈结构空间复杂度O(log(n))

Runtime: 40 ms, faster than 21.58% of Python online submissions for Minimum Depth of Binary Tree.

Memory Usage: 14.9 MB, less than 20.51% of Python online submissions for Minimum Depth of Binary Tree.

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值