Python Runtime problems


  • 0
    V

    My DFS solution:

    from itertools import repeat
    
    
    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    
    class GraphNode:
        def __init__(self, value):
            self.val = value
            self.adjacent = []
    
    
    class Solution(object):
        def maxPathSum(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root:
                return 0
    
            nodes = set()
            self.convert_tree_graph(root, None, nodes)
    
            cache = {}
            max_path_so_far = 0
            for node in nodes:
                visited = set()
                cmaxpath = self.get_max_path(node, cache, visited)
                if cmaxpath > max_path_so_far:
                    max_path_so_far = cmaxpath
    
            return max_path_so_far
    
        def get_max_path(self, node, cache, visited):
            visited.add(node)
            nodes_to_visit = list(filter(lambda x: x not in visited, node.adjacent))
    
            if not nodes_to_visit:
                return node.val
    
            cacheitem = (node, frozenset(nodes_to_visit))
    
            if cacheitem not in cache:
                cache[cacheitem] = max(map(self.get_max_path,
                                           nodes_to_visit, repeat(cache), repeat(visited))) + node.val
    
            return cache[cacheitem]
    
        def convert_tree_graph(self, root, parent, nodes):
            # if not root:
            #     return
    
            newnode = GraphNode(root.val)
            nodes.add(newnode)
    
            if parent:
                newnode.adjacent.append(parent)
    
            if root.left:
                newnode.adjacent.append(self.convert_tree_graph(root.left, newnode, nodes))
    
            if root.right:
                newnode.adjacent.append(self.convert_tree_graph(root.right, newnode, nodes))
    
            return newnode
    

    The problem is that OJ is responding with:

    Runtime Error Message:
    Line 39: AttributeError: 'NoneType' object has no attribute 'adjacent'

    Last executed input:
    [1,2,3]

    But I can't replicate problem locally. I've tried running it with same and similar tries and everything works just fine. I would be glad if somebody can point out what am I missing here.
    Thank you!


Log in to reply
 

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