[leetcode] 111. Minimum Depth of Binary Tree @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87864292

原题

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.

解法1

DFS, 从根节点开始遍历树, 将所有的path加到res里, 然后对res排序, 以path的长度升序排列, 返回res[0]的长度即可
Time: O(n)
Space: O(n)

代码

# 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':
        # base case
        if not root: return 0
        res = []
        
        def dfs(root, path, res):
            if not root:
                return
            if root.left is None and root.right is None:
                path.append(root.val)
                res.append(path)
            dfs(root.left, path+[root.val], res)
            dfs(root.right, path+[root.val], res)
            
        dfs(root, [], res)
        res.sort(key = lambda x: len(x))
        return len(res[0])

解法2

递归

Time: O(n)
Space: O(1)

代码

# 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':
        # base case
        if not root: return 0
        if root.left is None:
            return 1 + self.minDepth(root.right)
        if root.right is None:
            return 1 + self.minDepth(root.left)
        else:
            return min(self.minDepth(root.left), self.minDepth(root.right)) + 1

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/87864292