ntree.ai
ntree.aiClone Graph

Clone Graph

mediumsolvedattempted

Given a node of a connected, undirected graph, return a deep copy of the whole graph. You should create new nodes with the same values and edges.

Example 1:

1
2
3
4
Input:  node = [[2], [1, 3, 4], [2, 4], [2, 3]]
Output: [[2], [1, 3, 4], [2, 4], [2, 3]]
Explanation: The example graph is shown as an adjacency list, where the element at index i names the neighbours of node i + 1.

Constraints:

  • 1 <= number of nodes <= 100
  • 1 <= Node.val <= 100, and every value is different
# Definitions:
# class GraphNode:
# def __init__(self, val=0, neighbors=None):
# self.val = val
# self.neighbors = neighbors if neighbors is not None else []
 
def cloneGraph(node: GraphNode) -> GraphNode:
pass
 
1
2
3
4

Press Visualise to step through your code.