Very short recursive Java solution/DFS


  • 0

    Uses a map to keep track of visited nodes and already created node copy.

    public class Solution {
        private Map<RandomListNode, RandomListNode> visited = new HashMap<>();
        public RandomListNode copyRandomList(RandomListNode head) {
            if (head == null || visited.containsKey(head)) {
                return (head == null) ? null : visited.get(head);
            }
            RandomListNode newHead = new RandomListNode(head.label);
            visited.put(head, newHead);
            newHead.random = copyRandomList(head.random);
            newHead.next = copyRandomList(head.next);
            return newHead;
        }
    }
    

Log in to reply
 

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