Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
What is the mistake in this code - Clone a graph . It says
Object Reference not set to an instance of an object in LeetCode for this line - target.Add(C);.
Could someone share some suggestions here.
public class Node {
public int val;
public IList<Node> neighbors;
public Node(){}
public Node(int _val,IList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;}
public class Solution {
public Node CloneGraph(Node node) {
if (node == null)
{return null;}
var map = new Dictionary<int, Node>();
Queue<Node> q = new Queue<Node>();
q.Enqueue(node);
Node newNode = new Node();
newNode.val = node.val;
CopyList(node.neighbors,newNode.neighbors);
map.Add(newNode.val, newNode);
while(q.Count!=0)
{
Node head = q.Dequeue();
Node cloneU = map[head.val];
foreach (Node neighborNode in head.neighbors)
{
if(map.ContainsKey(neighborNode.val))
{
CopyList(head.neighbors,cloneU.neighbors);
}
else
{
q.Enqueue(neighborNode);
Node neighborNodeCopy = new Node(neighborNode.val,neighborNode.neighbors);
map.Add(neighborNodeCopy.val, neighborNodeCopy);
CopyList(neighborNodeCopy.neighbors,cloneU.neighbors);
}
}
}
return newNode;
}
public void CopyList(IList<Node> source, IList<Node> target)
{
foreach( Node C in source)
{
target.Add(C);
}
}
}