diff --git a/core/src/main/kotlin/org/jetbrains/jewel/foundation/tree/Tree.kt b/core/src/main/kotlin/org/jetbrains/jewel/foundation/tree/Tree.kt index 27e29cbd9..89649c200 100644 --- a/core/src/main/kotlin/org/jetbrains/jewel/foundation/tree/Tree.kt +++ b/core/src/main/kotlin/org/jetbrains/jewel/foundation/tree/Tree.kt @@ -1,14 +1,37 @@ package org.jetbrains.jewel.foundation.tree +import org.jetbrains.jewel.foundation.tree.Tree.Element.Node + @Suppress("UNCHECKED_CAST") fun emptyTree() = Tree.EMPTY as Tree -class Tree internal constructor(internal val roots: List>) { +class Tree internal constructor(val roots: List>) { companion object { internal val EMPTY = Tree(roots = emptyList>()) } + fun isEmpty() = roots.isEmpty() + + private fun walk(breathFirst: Boolean) = sequence { + val queue = roots.toMutableList() + while (queue.isNotEmpty()) { + val next = queue.removeFirst() + yield(next) + if (next is Node) { + next.open() + if (breathFirst) { + queue.addAll(next.children.orEmpty()) + } else { + queue.addAll(0, next.children.orEmpty()) + } + } + } + } + + fun walkBreadthFirst() = walk(true) + fun walkDepthFirst() = walk(false) + sealed interface Element { val data: T