leetcode 104. Maximum Depth of Binary Tree
My first try is write like this, but the final return value is 0 although in the recursive function depth increased to correct value.
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
depth = 0
def mxdp(root,depth):
if root:
depth += 1
print(root.val,depth)
if root.left:
mxdp(root.left,depth)
if root.right:
mxdp(root.right,depth)
mxdp(root,depth)
print(depth)
return depth
Then I try to use global variable after read some online article, below is my 2nd version, but it give me an error: name 'depth' is not defined at this line: depth += 1
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
depth = 0
def mxdp(root):
global depth
if root:
depth += 1
if root.left:
mxdp(root.left)
if root.right:
mxdp(root.right)
mxdp(root)
return depth
Could you please teach me why none of these two ways are not working? How to write correctly? Thanks!