当前位置:网站首页>Xiaohei's leetcode journey: 104. The maximum depth of a binary tree

Xiaohei's leetcode journey: 104. The maximum depth of a binary tree

2022-07-31 00:59:00 little black invincible

Little black solution one:深度优先

# 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 maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        def getDepth(node):
            if node:
                return max(getDepth(node.left),getDepth(node.right)) + 1
            else:
                return 0
        return getDepth(root)

在这里插入图片描述

Little black solution 2:宽度优先

# 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 maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        q = collections.deque([root])
        depth = 0
        while q:
            # The number of nodes in the queue
            n = len(q)
            for i in range(n):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            depth += 1
        return depth

在这里插入图片描述

原网站

版权声明
本文为[little black invincible]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/212/202207310051550363.html