Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created September 11, 2022 20:18
Show Gist options
  • Save ZhouYang1993/e8fcdaeb2841f61d35ca2ccd66550234 to your computer and use it in GitHub Desktop.
Save ZhouYang1993/e8fcdaeb2841f61d35ca2ccd66550234 to your computer and use it in GitHub Desktop.
deque in Python
# 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