Created
September 11, 2022 20:18
-
-
Save ZhouYang1993/e8fcdaeb2841f61d35ca2ccd66550234 to your computer and use it in GitHub Desktop.
deque in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
from collections import deque | |
class Solution: | |
def maxDepth(self, root: Optional[TreeNode]) -> int: | |
depth = 0 | |
queue = deque([root]) | |
while queue: | |
next_layer = 0 | |
for _ in range(len(queue)): | |
node = queue.popleft() | |
if node: | |
next_layer = 1 | |
queue.append(node.left) | |
queue.append(node.right) | |
if next_layer: | |
depth += 1 | |
return depth |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment