[Leetcode]Minimum Depth of Binary Tree

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.

判断树的最小深度~树的最小深度指的是从根节点到最近的叶节点的距离,所以如果某一个节点只有左子树或右子树,我们不能取它左右子树中小的作为深度,因为其并非叶节点,要注意处理这种情况~下面代码是递归的解法~

class Solution:
    # @param root, a tree node
    # @return an integer
    def minDepth(self, root):
        if root is None: return 0
        if root.left is None: return self.minDepth(root.right) + 1
        if root.right is None: return self.minDepth(root.left) + 1
        return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

知道递归解法还不够,最好也能写出非递归解法~代码如下~(注意:python中list.pop(0)时间复杂度为O(n),所以下面curr = queue.pop(0)这句不是很高效)

class Solution:
    # @param root, a tree node
    # @return an integer
    def minDepth(self, root):
        if root is None: return 0
        queue = [root, None]; depth = 1
        while queue:
            curr = queue.pop(0)
            if curr == None:
                # note: do not increase depth if queue
                #   is empty; 
                if queue:
                    queue.append(None)
                    depth += 1
            else:
                if curr.left is None and curr.right is None:
                    return depth
                if curr.left:
                    queue.append(curr.left)
                if curr.right:
                    queue.append(curr.right)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值