Runtime TypeError with python


  • 0
    T

    This is my primitive code for binary tree preorder traversal using recursion. However, TypeErrors often occur. But I'm not sure what is the best way to assert proper types for function arguments.

    # Definition for a  binary tree node
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param root, a tree node
        # @return a list of integers
        def preorderTraversal(self, root):
            if not root:
                return []
            else:
                return list(root.val) + \
                    self.preorderTraversal(root.left) + \
                    self.preorderTraversal(root.right)
    

    The judgement result was:
    Runtime Error Message: Line 16: TypeError: 'int' object is not iterable
    Last executed input: {1}

    Looking forward to comments and suggestions. Thanks!


  • 0
    S

    Not familiar with python, but change your code from return list(root.val) + \ to return [root.val] + \, then it works.


  • 0
    T

    Great! Thanks a lot.
    It seems that you are more familiar with python than me. =)


  • 0
    S

    lol, but I just think list() should be ok as well. You might need to figure out what's the difference between them.


  • 0
    T

    I searched online and found that the list() is used to convert a given tuple into list.
    url: http://www.tutorialspoint.com/python/list_list.htm


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.