I am solving the following Leetcode problem: https://leetcode.com/problems/maximum-depth-of-binary-tree/solution/
It is to return the maximum depth of a binary tree.
Here is my solution:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
stack = [(root, 1)]
curr_depth = 1
while stack:
node, depth = stack.pop()
depth = max(curr_depth,depth)
if node.right:
stack.append((node.right, curr_depth + 1))
if node.left:
stack.append((node.left, curr_depth + 1))
return depth
For some reason the output is always one less than it is supposed to be. And looking at the accepted solutions, they look very similar to mine, but I can't seem to find where my solution is going wrong.