Skip to content

Latest commit

 

History

History
89 lines (68 loc) · 1.91 KB

_1490. Clone N-ary Tree.md

File metadata and controls

89 lines (68 loc) · 1.91 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


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 %


Solutions

Java

/*
// 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);
    }
}

Python

"""
# 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)