1490. Clone N-ary Tree
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 02, 2024
Last updated : July 01, 2024
Related Topics : Hash Table, Tree, Depth-First Search, Breadth-First Search
Acceptance Rate : 83.13 %
/*
// 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;
}
ArrayList<Node> newChildren = new ArrayList<>();
for (Node i: root.children) {
newChildren.add(cloneTree(i));
}
return new Node(root.val, newChildren);
}
}
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
"""
class Solution:
def cloneTree(self, root: 'Node') -> 'Node':
if not root:
return None
children = []
for i in root.children :
children.append(self.cloneTree(i))
return Node(root.val, children)