Skip to content

Instantly share code, notes, and snippets.

@ThomasHigginson
Last active April 4, 2022 15:01
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/030667cefc5fa8e1fc53db7aa36f5937 to your computer and use it in GitHub Desktop.
Save ThomasHigginson/030667cefc5fa8e1fc53db7aa36f5937 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
stack = [(root, 1)] # (Node, depth of Node)
maxDepth = 1
while stack:
node, depth = stack.pop()
maxDepth = max(maxDepth, depth)
if node.left:
stack.append((node.left, depth+1))
if node.right:
stack.append((node.right, depth+1))
return maxDepth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment