首页 > 其他 > 详细

1490. Clone N-ary Tree

时间:2020-07-13 01:11:43      阅读:91      评论:0      收藏:0      [点我收藏+]
package LeetCode_1490

/**
 * 1490. Clone N-ary Tree
 * (Prime)
 * 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.
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?
 * */
class Node(var `val`: Int) {
    var children: List<Node>? = null
}

class Solution {
    fun cloneTree(root: Node?): Node? {
        if (root == null) {
            return null
        }
        val copy = Node(root.`val`)
        val children = ArrayList<Node>()
        for (child in root.children!!) {
            val childClone = cloneTree(child)
            if (childClone != null) {
                children.add(childClone)
            }
        }
        copy.children = children
        return copy
    }
}

 

1490. Clone N-ary Tree

原文:https://www.cnblogs.com/johnnyzhao/p/13290896.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!