LeetCode(力扣)111. 二叉树的最小深度Python

LeetCode111. 二叉树的最小深度

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/minimum-depth-of-binary-tree/
LeetCode(力扣)111. 二叉树的最小深度Python_第1张图片

代码

递归法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        return self.getmin(root)
    
    def getmin(self, node):
        if not node:
            return 0
        leftnode = self.getmin(node.left)
        rightnode = self.getmin(node.right)

        if node.left is None and node.right is not None:
            return 1 + rightnode

        if node.right is None and node.left is not None:
            return 1 + leftnode

        result = 1 + min(leftnode, rightnode)

        return result

迭代法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        depth = 0
        queue = collections.deque([root])
        
        while queue:
            depth += 1 
            for _ in range(len(queue)):
                node = queue.popleft()
                
                if not node.left and not node.right:
                    return depth
            
                if node.left:
                    queue.append(node.left)
                    
                if node.right:
                    queue.append(node.right)

        return depth

你可能感兴趣的:(leetcode,python,算法,linux,职场和发展)