Run time error in my Python code


  • 0
    L

    Runtime Error Message: Line 30: AttributeError: 'NoneType' object has no attribute 'append'
    Last executed input: {1}

        # 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 lists of integers
        def levelOrder(self, root):
            res=""
            if root:
                q=[]
                q.append(root)
             # to generate the string of the tree 
                while q:
                    tmp = q.pop()
                    if tmp:
                        res=res+str(tmp.val)
                        q.append(tmp.left)
                        q.append(tmp.right)
                    else:
                        res=res+'#'
            # from the string list to generate the list of numbers
            # basically the length of string is two time of existing notes in the previous lyer
            res1=[]
            index, range = 0, 1
            while index<len(res):
                tmp = [x for x in res[index:index+range] if x.isdigit()]
                res1=res1.append(tmp)
                index=index+range
                range=2*len(tmp) if len(res)-index>2*len(tmp) else len(res)-index
            return res1

  • 0
    C

    Change

    res1=res1.append(tmp)
    

    to

    res1.append(tmp)
    

    append() modifies the given list and returns None. So your satement result in res1=None after the first pass of the iteration. The second pass result in error because the res1 is not referencing the list anymore.


Log in to reply
 

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