-1
from typing import Optional
class Solution:
    def findLeaves(self,root: Optional[TreeNode]) -> list[list[int]]:
        def post_order(node):
            nonlocal lookup

            if not node:
                return 0
            left_depth = post_order(node.left)
            right_depth = post_order(node.right)
            curr_depth = max(left_depth,right_depth) + 1
            lookup(curr_depth).append(node.val)
            return curr_depth
        lookup = defaultdict(list)
        post_order(root)
        return lookup.values()

demo = Solution()
root = [1,2,3,4,5]

v = demo.findLeaves(root)
print(v)

After running, the following error is reported:

Traceback (most recent call last):
  File "E:\pythonProject\LeetCode\366_find_leaf_nodes.py", line 2, in <module>
    class Solution:
  File "E:\pythonProject\LeetCode\366_find_leaf_nodes.py", line 3, in Solution
    def findLeaves(self,root: TreeNode) -> list[list[int]]:
NameError: name 'TreeNode' is not defined**
Vitalizzare
  • 4,496
  • 7
  • 13
  • 32
  • Why did you specify that the type of the `root` parameter is `Optional[TreeNode]`? That's an outright lie - no such type as `TreeNode` has been defined, and you're passing an ordinary list for that parameter anyway. – jasonharper Aug 26 '22 at 14:30
  • What have you tried so far to solve the problem? I don’t see any effort from you – Hi computer Sep 03 '22 at 06:33

1 Answers1

0

TreeNode is a class defined by LeetCode. You need to copy their class definition, given in comments at the top of the code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

You also need to structure the test case as a TreeNode rather than a list.

RapidIce
  • 51
  • 1
  • 3