How to clone/copy N-ary tree iteratively, without recursion? Just need to rewrite cloneRecursive function iteratively:
import java.util.ArrayDeque
sealed class Row {
abstract val name: String
data class Section(override val name: String, val rows: List<Row>) : Row()
data class Field(override val name: String, val data: String) : Row()
}
fun main() {
val root = Row.Section(
"root", listOf(
Row.Section(
"section 1", listOf(
Row.Section(
"section 1.1", listOf(
Row.Field("field 1.1.1", "1.1.1 - 1"),
Row.Field("field 1.1.2", "1.1.2 - 1")
)
),
Row.Field("field 1.2", "1.2 - 1")
)
),
Row.Field("field 2", "2 - 1"),
Row.Field("field 3", "3 - 1"),
Row.Section(
"section 4", listOf(
Row.Field("field 4.1", "4.1 - 1"),
Row.Field("field 4.2", "4.2 - 1"),
Row.Section(
"section 4.3", listOf(
Row.Field("field 4.3.1", "4.3.1 - 1"),
Row.Field("field 4.3.2", "4.3.2 - 1")
)
)
)
)
)
)
println(root)
println(recursiveClone(root))
println(root == recursiveClone(root))
}
fun recursiveClone(root: Row): Row {
return when (root) {
is Row.Section -> {
val rows = root.rows.map { row ->
recursiveClone(row)
}
Row.Section(root.name, rows)
}
is Row.Field -> {
Row.Field(root.name, root.data)
}
}
}