Python with dfs and dict, 84ms


  • 0
    V

    Nothing special as far as I concerned. Just got message "Your runtime beats 100.00% of python coders." (84ms) And decided to post the code.

    class Solution(object):
        def __init__(self):
            self.cloned = {}
    
        def cloneGraph(self, node):
            """
            :type node: UndirectedGraphNode
            :rtype: UndirectedGraphNode
            """
            if not node:
                return None
    
            new_root = UndirectedGraphNode(node.label)
            self.clone_graph_rec(node, new_root)
    
            return new_root
    
        def clone_graph_rec(self, original_node, new_node):
            self.cloned[original_node] = new_node
            for child_node in original_node.neighbors:
                if not child_node in self.cloned:
                    new_child = UndirectedGraphNode(child_node.label)
                    self.clone_graph_rec(child_node, new_child)
    
                new_node.neighbors.append(self.cloned[child_node])

Log in to reply
 

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