Skip to content

Instantly share code, notes, and snippets.

@ponnamkarthik
Created August 5, 2023 08:42
Show Gist options
  • Save ponnamkarthik/d774dd2e7a3756b69384034eb491c9c2 to your computer and use it in GitHub Desktop.
Save ponnamkarthik/d774dd2e7a3756b69384034eb491c9c2 to your computer and use it in GitHub Desktop.
Maximum Depth of Binary Tree - BFS
# 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
# BFS
q = deque()
q.append(root)
level = 0
while q:
for i in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
level += 1
return level
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment