The following is my code. I just can't understand why it prompts an error about global name.
class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ depth = 1 def node_search(node,count): global depth if node.left: node = node.left count += 1 node_search(node,count) if node.right: node = node.right count += 1 node_search(node,count) depth = max(depth,count) # line 26 if root: node_search(root,depth) return depth else: return 0
Line 26: NameError: global name 'depth' is not defined
I think it is because I missed some "self." when I called the member functions and used member variables.
This seems to be a pretty old post, but here are my comments -
You've declared depth inside the function and not in your class. You wouldn't have to use global depth in any case since the variable is inside the class.
To refer to depth in node_search, try self.maxDepth.depth
If that doesn't work, you can declare depth right after class Solution(object), and when you want to use in node_search, you can do self.depth
Please let me know if that works!
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.