LeetCode111. 二叉树的最小深度 (BFS) + (递归)两种方法

LeetCode111. 二叉树的最小深度 (BFS) + (递归)两种方法

BFS

# 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 not root:
            return 0
        q = []
        q.append(root)
        ans = 1
        while q:
            tmp = []
            for i in q:
                if i.left:
                    tmp.append(i.left)
                if i.right:
                    tmp.append(i.right)
                if not i.left and not i.right:
                    return ans
            ans +=1
            q = tmp
        return ans

递归

# 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 not root:
            return 0
        l = self.minDepth(root.left) + 1
        r = self.minDepth(root.right) + 1
        if root.left and root.right:
            return min(l, r)
        elif root.left:
            return l
        else:
            return r
    

猜你喜欢

转载自blog.csdn.net/qq_42991793/article/details/87936348