The depth of the n-ary tree is less than or equal to 1000.
The total number of nodes is between [0, 104].
Follow up: Can your solution work for the graph problem?
Solutions
Solution 1
1 2 3 4 5 6 7 8 9101112131415
"""# 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 []"""classSolution:defcloneTree(self,root:'Node')->'Node':ifrootisNone:returnNonechildren=[self.cloneTree(child)forchildinroot.children]returnNode(root.val,children)
/*// 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; }};*/classSolution{publicNodecloneTree(Noderoot){if(root==null){returnnull;}ArrayList<Node>children=newArrayList<>();for(Nodechild:root.children){children.add(cloneTree(child));}returnnewNode(root.val,children);}}
/*// Definition for a Node.class Node {public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; }};*/classSolution{public:Node*cloneTree(Node*root){if(!root){returnroot;}vector<Node*>children;for(Node*child:root->children){children.emplace_back(cloneTree(child));}returnnewNode(root->val,children);}};
1 2 3 4 5 6 7 8 9101112131415161718
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */funccloneTree(root*Node)*Node{ifroot==nil{returnnil}children:=[]*Node{}for_,child:=rangeroot.Children{children=append(children,cloneTree(child))}return&Node{root.Val,children}}