Skip to content

Commit

Permalink
Implement tree traversal methods in Tree class (#135)
Browse files Browse the repository at this point in the history
* Implement tree traversal methods in Tree class

Enhanced the Tree class in the jewel foundation by adding two new methods for performing tree traversal: 'walkBreadthFirst' and 'walkDepthFirst'. These enhancements provide flexibility in tree exploration based on the application needs. Modifying the 'roots' variable from 'internal' to 'val' to facilitate tree manipulation.

* Refactor conditional statements in Tree.kt
  • Loading branch information
lamba92 authored Sep 27, 2023
1 parent 3110fb2 commit 6b59bb9
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion core/src/main/kotlin/org/jetbrains/jewel/foundation/tree/Tree.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
package org.jetbrains.jewel.foundation.tree

import org.jetbrains.jewel.foundation.tree.Tree.Element.Node

@Suppress("UNCHECKED_CAST")
fun <T> emptyTree() = Tree.EMPTY as Tree<T>

class Tree<T> internal constructor(internal val roots: List<Element<T>>) {
class Tree<T> internal constructor(val roots: List<Element<T>>) {

companion object {
internal val EMPTY = Tree(roots = emptyList<Element<Any?>>())
}

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<T> {

val data: T
Expand Down

0 comments on commit 6b59bb9

Please sign in to comment.