美文网首页
[Tree]111. Minimum Depth of Bina

[Tree]111. Minimum Depth of Bina

作者: 野生小熊猫 | 来源:发表于2019-02-23 03:45 被阅读0次
  • 分类:Tree
  • 时间复杂度: O(n) 这种把树的节点都遍历一遍的情况时间复杂度为O(n)
  • 空间复杂度: O(h) 树的节点的深度

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

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.

代码:

# 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 root==None:
            return 0
        
        return self.helper(root,1)
    
    def helper(self,root,level):
        level+=1
        if root.left==None and root.right==None:
            return level-1
        elif root.left==None:
            return self.helper(root.right,level)
        elif root.right==None:
            return self.helper(root.left,level)
        else:
            return min(self.helper(root.left,level),self.helper(root.right,level))

讨论:

1.虽然折腾了半天,但是这个代码是自己写的还是非常自豪滴!

相关文章

网友评论

      本文标题:[Tree]111. Minimum Depth of Bina

      本文链接:https://www.haomeiwen.com/subject/eyluyqtx.html