A java recursive solution, as the same as clone a graph


  • 0
    F
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
            return copyhelper(head, map);
        }
        public RandomListNode copyhelper(RandomListNode head, Map<RandomListNode, RandomListNode> map){
            if (head == null) return null;
            RandomListNode tmp = new RandomListNode(head.label);
            map.put(head, tmp);
            if (head.next != null) {
                if (!map.containsKey(head.next)) tmp.next = copyhelper(head.next, map);
                else tmp.next = map.get(head.next);
            }
            if (head.random != null) {
                if (!map.containsKey(head.random)) tmp.random = copyhelper(head.random, map);
                else tmp.random = map.get(head.random);
            }
            return tmp;
        }
    }
    

Log in to reply
 

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