LeetCode 1490: Clone N-ary Tree
Problem Description
Explanation:
To clone an N-ary tree, we need to create a deep copy of each node in the tree along with all its children. We can solve this problem using a recursive approach where we traverse the original tree and create a new node for each visited node while recursively cloning its children.
- Create a helper function
cloneNode
to clone a single node by creating a new node with the same value and an empty list of children. - Traverse the original tree using a recursive function
cloneTree
that clones each node and its children. - Return the cloned tree root node.
: :
Solutions
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int val) {
this.val = val;
}
public Node(int val, List<Node> children) {
this.val = val;
this.children = children;
}
}
class Solution {
public Node cloneNode(Node node) {
if (node == null) return null;
Node clone = new Node(node.val, new ArrayList<>());
for (Node child : node.children) {
clone.children.add(cloneNode(child));
}
return clone;
}
public Node cloneTree(Node root) {
if (root == null) return null;
return cloneNode(root);
}
}
Loading editor...