Skip to content

Instantly share code, notes, and snippets.

@ThomasHigginson
Created April 4, 2022 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasHigginson/7cd3cbe66b4dba92dea52f717641d90d to your computer and use it in GitHub Desktop.
Save ThomasHigginson/7cd3cbe66b4dba92dea52f717641d90d to your computer and use it in GitHub Desktop.
# Iterative DFS solution using a stack
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
dque = deque([root])
nodes_at_curr_depth = len(dque)
depth = 1
while dque:
node = dque.popleft()
if node.left:
dque.append(node.left)
if node.right:
dque.append(node.right)
nodes_at_curr_depth -= 1
if nodes_at_curr_depth == 0: # Visited all for this depth
depth += 1
nodes_at_curr_depth = len(dque) # Remaining nodes are at next depth
return depth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment