C# iterative solution


  • 0
    H
    public UndirectedGraphNode CloneGraph(UndirectedGraphNode root) {
            if (root == null) return null;
            
            Dictionary<UndirectedGraphNode, UndirectedGraphNode> map = new Dictionary<UndirectedGraphNode, UndirectedGraphNode>();
            Stack<UndirectedGraphNode> stack = new Stack<UndirectedGraphNode>();
            map[root] = new UndirectedGraphNode(root.label);
            stack.Push(root);
            while(stack.Count > 0) {
                UndirectedGraphNode node = stack.Pop();
                foreach(UndirectedGraphNode neighbor in node.neighbors) {
                    if (!map.ContainsKey(neighbor)) {
                        map[neighbor] = new UndirectedGraphNode(neighbor.label);
                        stack.Push(neighbor);
                    } 
                    map[node].neighbors.Add(map[neighbor]);
                }
            }
            
            return map[root];
        }
    

Log in to reply
 

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