104. 二叉树的最大深度

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

解法一:层序

每层深度+1

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import queue
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        depth = 0
        q = queue.Queue()
        q.put(root)
        while not q.empty():
            count = q.qsize()
            depth += 1
            for _ in range(count):
                node = q.get()
                if node.left:
                    q.put(node.left)
                if node.right:
                    q.put(node.right)
        return depth

最后更新于