[LeetCode] 1490. Clone N-ary Tree
Given a root
of an N-ary tree, return a deep copy (clone) of the tree.
Each node in the n-ary tree contains a val (int
) and a list (List[Node]
) of its children.
class Node { public int val; public List<Node> children; }
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Follow up: Can your solution work for the graph problem?
Example 1:
Input: root = [1,null,3,2,4,null,5,6] Output: [1,null,3,2,4,null,5,6]Example 2:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Constraints:
- The depth of the n-ary tree is less than or equal to
1000
. - The total number of nodes is between
[0, 10^4]
.
克隆N叉树。题目就是题意。这道题有两种做法,BFS和DFS,两种做法的时间和空间复杂度都是O(n)。建议可以先做一下133题,熟悉一下克隆是怎么一回事。
DFS
对递归有感觉的同学会发现DFS的思路很容易做。首先自然是clone一下当前遇到的节点,得到copy节点;对于当前节点的所有孩子,不光需要为这每一个孩子clone一份,同时也要把这些clone的孩子放到copy节点的children指针上。
1 class Solution { 2 public Node cloneTree(Node root) { 3 // corner case 4 if (root == null) { 5 return null; 6 } 7 // normal case 8 Node copy = new Node(root.val); 9 for (Node child : root.children) { 10 copy.children.add(cloneTree(child)); 11 } 12 return copy; 13 } 14 }
BFS
既然是BFS,肯定是需要用到一个队列queue去遍历所有的节点。遍历的时候,需要为每一个遍历到的节点clone一份,并用hashmap记录原生版本和复制版本的对应关系;同时,在遍历每个节点的children们的时候,需要clone每一个孩子节点,用hashmap记录原生版本和复制版本的对应关系,同时需要把clone的孩子加到当前节点的clone的children指针上。
1 class Solution { 2 public Node cloneTree(Node root) { 3 // corner case 4 if (root == null) { 5 return null; 6 } 7 // normal case 8 HashMap<Node, Node> map = new HashMap<>(); 9 Queue<Node> queue = new LinkedList<>(); 10 queue.offer(root); 11 while (!queue.isEmpty()) { 12 int size = queue.size(); 13 for (int i = 0; i < size; i++) { 14 // 复制当前节点并记录clone关系 15 Node cur = queue.poll(); 16 Node curCopy = map.getOrDefault(cur, new Node(cur.val)); 17 map.put(cur, curCopy); 18 // 遍历孩子节点 19 for (Node child : cur.children) { 20 queue.offer(child); 21 Node childCopy = map.getOrDefault(child, new Node(child.val)); 22 curCopy.children.add(childCopy); 23 map.put(child, childCopy); 24 } 25 } 26 } 27 return map.get(root); 28 } 29 }
相关题目
138. Copy List with Random Pointer