提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣1485. 克隆含随机指针的二叉树
- 二、力扣1490. 克隆 N 叉树
- 三、力扣133. 克隆图
- 四、力扣138. 随机链表的复制
前言
复制带有随机指针的二叉树或者链表,或者图,先设置一个map作为映射,原节点与复制后节点的映射,然后正常的遍历返回节点,但需要注意的是,遍历顺序,先遍历其他节点,最后遍历随机节点,因为随机节点可能没有被创建,遍历其他节点时,创建复制节点,遍历随机节点时,查找映射关系返回
一、力扣1485. 克隆含随机指针的二叉树
/*** Definition for Node.* public class Node {* int val;* Node left;* Node right;* Node random;* Node() {}* Node(int val) { this.val = val; }* Node(int val, Node left, Node right, Node random) {* this.val = val;* this.left = left;* this.right = right;* this.random = random;* }* }*/class Solution {HashMap<Node,NodeCopy> map = new HashMap<>();public NodeCopy copyRandomBinaryTree(Node root) {if(root == null){return null;}if(map.containsKey(root)){return map.get(root);}NodeCopy cur = new NodeCopy(root.val);map.put(root,cur);cur.left = copyRandomBinaryTree(root.left);cur.right = copyRandomBinaryTree(root.right);cur.random = copyRandomBinaryTree(root.random);return cur;}
}
二、力扣1490. 克隆 N 叉树
/*
// Definition for a Node.
class Node {public int val;public List<Node> children;public Node() {children = new ArrayList<Node>();}public Node(int _val) {val = _val;children = new ArrayList<Node>();}public Node(int _val,ArrayList<Node> _children) {val = _val;children = _children;}
};
*/class Solution {public Node cloneTree(Node root) {if(root == null){return null;}Node cur = new Node(root.val);cur.children = new LinkedList<Node>();for(Node n : root.children){Node c = cloneTree(n);cur.children.add(c);}return cur;}
}
三、力扣133. 克隆图
/*
// Definition for a Node.
class Node {public int val;public List<Node> neighbors;public Node() {val = 0;neighbors = new ArrayList<Node>();}public Node(int _val) {val = _val;neighbors = new ArrayList<Node>();}public Node(int _val, ArrayList<Node> _neighbors) {val = _val;neighbors = _neighbors;}
}
*/class Solution {HashSet<Node> visited = new HashSet<>();Map<Node,Node> originToClone = new HashMap<>();public Node cloneGraph(Node node) {traverse(node);return originToClone.get(node);}void traverse(Node node){if(node == null){return;}if(visited.contains(node)){return;}visited.add(node);originToClone.put(node,new Node(node.val));Node copyNode = originToClone.get(node);for(Node n : node.neighbors){traverse(n);copyNode.neighbors.add(originToClone.get(n));}}
}
四、力扣138. 随机链表的复制
/*
// Definition for a Node.
class Node {int val;Node next;Node random;public Node(int val) {this.val = val;this.next = null;this.random = null;}
}
*/class Solution {Map<Node , Node> map = new HashMap<>();public Node copyRandomList(Node head) {if(head == null){return null;}if(map.containsKey(head)){return map.get(head);}Node cur = new Node(head.val);map.put(head,cur);cur.next = copyRandomList(head.next);cur.random = copyRandomList(head.random);return cur;}
}