Created
April 4, 2022 15:05
-
-
Save ThomasHigginson/7cd3cbe66b4dba92dea52f717641d90d to your computer and use it in GitHub Desktop.
This file contains 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
# 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