6 Commits

Author SHA1 Message Date
Adrian Kuta
f60a5c4a86 Release 4.1.0: structural mutations, query algorithms, customizable prettyString, immutable module
Some checks failed
Test / JVM / JS / Wasm / Native + API check (push) Has been cancelled
Test / iOS (push) Has been cancelled
2026-06-07 23:31:15 +02:00
Adrian Kuta
0b8429c859 ci: cache Gradle, harden permissions, fix test triggers (#45)
- Add gradle/actions/setup-gradle caching to all three workflows
- test.yml: trigger on pull_request + push to master (was branches-ignore: master), so PRs from forks are covered and master is verified after merge; add least-privilege permissions and PR-only concurrency
- publishRelease.yml: drop unused 'secrets: inherit' and the dead SNAPSHOT env var (Gradle reads the snapshot project property, not a plain env var); add contents: read permissions; fix the misleading Maven Central comment (upload only stages on Central Portal, the final Publish is manual)
- docs.yml: add Gradle caching
2026-06-07 23:25:55 +02:00
Adrian Kuta
f47fb091ec feat: add tree-structure-immutable module (persistent ImmutableTreeNode) (#33) (#44) 2026-06-07 22:40:41 +02:00
Adrian Kuta
6758a68522 feat: add customizable prettyString with renderer and connector styles (#36) (#43) 2026-06-07 22:38:30 +02:00
Adrian Kuta
30b2709803 feat: add tree query algorithms (lowestCommonAncestor/distance/pathBetween/contains) (#35) (#42) 2026-06-07 22:36:48 +02:00
Adrian Kuta
06eae4841e feat: add structural mutation helpers (insert/move/replace/sort children) (#34) (#41) 2026-06-07 22:35:04 +02:00
19 changed files with 1191 additions and 14 deletions

View File

@@ -26,6 +26,8 @@ jobs:
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
- name: Generate API docs
run: ./gradlew :dokkaGeneratePublicationHtml --console=plain
- name: Upload Pages artifact

View File

@@ -5,11 +5,12 @@ on:
# We'll run this workflow when a new GitHub release is created
types: [released]
permissions:
contents: read
jobs:
test:
uses: ./.github/workflows/test.yml
secrets: inherit
publish:
needs: test
@@ -24,8 +25,12 @@ jobs:
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
# Runs upload, and then closes & releases the repository
# Uploads & stages the release on Central Portal. The final "Publish"
# step is manual there, because build.gradle.kts sets
# publishToMavenCentral(automaticRelease = false).
- name: Publish to MavenCentral
run: ./gradlew publishToMavenCentral
env:
@@ -33,4 +38,3 @@ jobs:
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }}
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_KEY }}
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }}
SNAPSHOT: false

View File

@@ -2,9 +2,17 @@ name: Test
on:
push:
branches-ignore: [master]
branches: [master]
pull_request:
workflow_call:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
test:
name: ${{ matrix.name }}
@@ -27,5 +35,7 @@ jobs:
with:
distribution: temurin
java-version: '21'
- name: Set up Gradle
uses: gradle/actions/setup-gradle@v4
- name: Test
run: ./gradlew ${{ matrix.tasks }} --console=plain

View File

@@ -6,6 +6,21 @@ All notable changes to this project are documented here. The format is based on
## [Unreleased]
## [4.1.0] - 2026-06-07
### Added
- Structural mutation helpers on `TreeNode`: `insertChild`, `removeChildAt`, `replaceChild`,
`moveChild`, `addChildren`, and `sortChildren`.
- Tree query extensions: `lowestCommonAncestor`, `distance`, `pathBetween`, and `contains` for
finding common ancestors, edge distances, the path between two nodes, and value membership.
- Customizable `prettyString(connectors, render)` extension: choose connector glyphs via
`TreeConnectors` (`Default` box-drawing or `Ascii`) and supply a per-node renderer that receives
the value, its depth and whether it is its parent's last child. The all-defaults call is
byte-identical to the existing no-arg `prettyString()`.
- New `tree-structure-immutable` module: a persistent `ImmutableTreeNode` with structural sharing
(`addChild`/`removeChild`/`mapValues` return new roots; pre/post/level-order traversals,
`nodeCount`, and `height`).
### Changed
- Rewrote the README for clarity: one consistent example tree, task-oriented sections
(building, traversal, navigation, functional, utilities, mutating), per-module usage, and a
@@ -76,7 +91,8 @@ A breaking release that cleans up the core API and enforces an explicit public s
## [3.1.3]
- iOS targets and Maven Central (Sonatype Central Portal) publishing.
[Unreleased]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v4.0.0...HEAD
[Unreleased]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v4.1.0...HEAD
[4.1.0]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v4.0.0...v4.1.0
[4.0.0]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v3.4.0...v4.0.0
[3.4.0]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v3.1.5...v3.4.0
[3.1.5]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v3.1.3...v3.1.5

View File

@@ -30,14 +30,14 @@ Gradle (Kotlin DSL):
```kotlin
// commonMain for KMP projects, or any sourceSet/module where you need it
dependencies {
implementation("com.github.adriankuta:tree-structure:4.0.0") // latest version is on the badge above
implementation("com.github.adriankuta:tree-structure:4.1.0") // latest version is on the badge above
}
```
Gradle (Groovy):
```groovy
dependencies {
implementation "com.github.adriankuta:tree-structure:4.0.0"
implementation "com.github.adriankuta:tree-structure:4.1.0"
}
```
@@ -46,7 +46,7 @@ Maven:
<dependency>
<groupId>com.github.adriankuta</groupId>
<artifactId>tree-structure</artifactId>
<version>4.0.0</version>
<version>4.1.0</version>
</dependency>
```
@@ -160,7 +160,7 @@ that depends on the core.
`@Serializable` directly. Convert to and from the acyclic `TreeNodeDto` instead.
```kotlin
implementation("com.github.adriankuta:tree-structure-serialization:4.0.0")
implementation("com.github.adriankuta:tree-structure-serialization:4.1.0")
```
```kotlin
val json = Json.encodeToString(root.toDto())
@@ -172,7 +172,7 @@ val restored = Json.decodeFromString<TreeNodeDto<String>>(json).toTreeNode()
Traverse a tree as a cold `Flow`, which is handy inside coroutine and `ViewModel` pipelines.
```kotlin
implementation("com.github.adriankuta:tree-structure-coroutines:4.0.0")
implementation("com.github.adriankuta:tree-structure-coroutines:4.1.0")
```
```kotlin
root.preOrderFlow().collect { println(it.value) }
@@ -185,7 +185,7 @@ A `LazyTree` composable for Compose Multiplatform (JVM/desktop, iOS, Wasm). Only
are composed, and you decide how each node looks:
```kotlin
implementation("com.github.adriankuta:tree-structure-compose:4.0.0")
implementation("com.github.adriankuta:tree-structure-compose:4.1.0")
```
```kotlin
LazyTree(root) { node, depth, expanded, toggle ->
@@ -196,6 +196,23 @@ LazyTree(root) { node, depth, expanded, toggle ->
}
```
### Immutable (`tree-structure-immutable`)
A persistent `ImmutableTreeNode` with structural sharing. Every operation (`addChild`,
`removeChild`, `mapValues`) returns a **new** root and leaves the original untouched; unchanged
subtrees are reused, so updates are cheap and old roots stay valid. Backed by
`kotlinx.collections.immutable`.
```kotlin
implementation("com.github.adriankuta:tree-structure-immutable:4.1.0")
```
```kotlin
val root = ImmutableTreeNode("World").addChild(ImmutableTreeNode("Europe"))
val bigger = root.addChild(ImmutableTreeNode("Asia")) // root is unchanged; bigger is a new tree
bigger.preOrder().forEach { println(it.value) } // pre/post/level-order, nodeCount(), height()
```
## Notes
`TreeNode` is mutable and not thread-safe. Add your own synchronization if you share a tree across

View File

@@ -6,10 +6,34 @@ public final class com/github/adriankuta/datastructure/tree/ChildDeclarationInte
public static synthetic fun child$default (Lcom/github/adriankuta/datastructure/tree/ChildDeclarationInterface;Ljava/lang/Object;Lkotlin/jvm/functions/Function1;ILjava/lang/Object;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
}
public final class com/github/adriankuta/datastructure/tree/TreeConnectors {
public static final field Companion Lcom/github/adriankuta/datastructure/tree/TreeConnectors$Companion;
public fun <init> (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
public final fun component1 ()Ljava/lang/String;
public final fun component2 ()Ljava/lang/String;
public final fun component3 ()Ljava/lang/String;
public final fun component4 ()Ljava/lang/String;
public final fun copy (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Lcom/github/adriankuta/datastructure/tree/TreeConnectors;
public static synthetic fun copy$default (Lcom/github/adriankuta/datastructure/tree/TreeConnectors;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/Object;)Lcom/github/adriankuta/datastructure/tree/TreeConnectors;
public fun equals (Ljava/lang/Object;)Z
public final fun getBranch ()Ljava/lang/String;
public final fun getEmpty ()Ljava/lang/String;
public final fun getLastBranch ()Ljava/lang/String;
public final fun getVertical ()Ljava/lang/String;
public fun hashCode ()I
public fun toString ()Ljava/lang/String;
}
public final class com/github/adriankuta/datastructure/tree/TreeConnectors$Companion {
public final fun getAscii ()Lcom/github/adriankuta/datastructure/tree/TreeConnectors;
public final fun getDefault ()Lcom/github/adriankuta/datastructure/tree/TreeConnectors;
}
public class com/github/adriankuta/datastructure/tree/TreeNode : com/github/adriankuta/datastructure/tree/ChildDeclarationInterface, java/lang/Iterable, kotlin/jvm/internal/markers/KMappedMarker {
public fun <init> (Ljava/lang/Object;Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;)V
public synthetic fun <init> (Ljava/lang/Object;Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public final fun addChild (Lcom/github/adriankuta/datastructure/tree/TreeNode;)V
public final fun addChildren ([Lcom/github/adriankuta/datastructure/tree/TreeNode;)V
public synthetic fun child (Ljava/lang/Object;Lkotlin/jvm/functions/Function1;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
public final fun clear ()V
public final fun depth ()I
@@ -19,13 +43,18 @@ public class com/github/adriankuta/datastructure/tree/TreeNode : com/github/adri
public final fun getTreeIterator ()Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;
public final fun getValue ()Ljava/lang/Object;
public final fun height ()I
public final fun insertChild (ILcom/github/adriankuta/datastructure/tree/TreeNode;)V
public final fun isRoot ()Z
public fun iterator ()Ljava/util/Iterator;
public final fun iterator (Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;)Ljava/util/Iterator;
public final fun moveChild (Lcom/github/adriankuta/datastructure/tree/TreeNode;I)Z
public final fun nodeCount ()I
public final fun path (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Ljava/util/List;
public final fun prettyString ()Ljava/lang/String;
public final fun removeChild (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Z
public final fun removeChildAt (I)Lcom/github/adriankuta/datastructure/tree/TreeNode;
public final fun replaceChild (ILcom/github/adriankuta/datastructure/tree/TreeNode;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
public final fun sortChildren (Ljava/util/Comparator;)V
public fun toString ()Ljava/lang/String;
}
@@ -51,6 +80,18 @@ public final class com/github/adriankuta/datastructure/tree/TreeNodeNavigationEx
public static final fun siblings (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Ljava/util/List;
}
public final class com/github/adriankuta/datastructure/tree/TreeNodePrettyPrintExtKt {
public static final fun prettyString (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/TreeConnectors;Lkotlin/jvm/functions/Function3;)Ljava/lang/String;
public static synthetic fun prettyString$default (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/TreeConnectors;Lkotlin/jvm/functions/Function3;ILjava/lang/Object;)Ljava/lang/String;
}
public final class com/github/adriankuta/datastructure/tree/TreeNodeQueryExtKt {
public static final fun contains (Lcom/github/adriankuta/datastructure/tree/TreeNode;Ljava/lang/Object;)Z
public static final fun distance (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/TreeNode;)Ljava/lang/Integer;
public static final fun lowestCommonAncestor (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
public static final fun pathBetween (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/TreeNode;)Ljava/util/List;
}
public final class com/github/adriankuta/datastructure/tree/TreeNodeSequenceExtKt {
public static final fun asSequence (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;)Lkotlin/sequences/Sequence;
public static synthetic fun asSequence$default (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;ILjava/lang/Object;)Lkotlin/sequences/Sequence;

View File

@@ -11,7 +11,7 @@ plugins {
val PUBLISH_GROUP_ID = "com.github.adriankuta"
val PUBLISH_ARTIFACT_ID = "tree-structure" // base artifact; KMP will add -jvm, -ios*, etc.
val PUBLISH_VERSION = "4.0.0"
val PUBLISH_VERSION = "4.1.0"
val snapshot: String? by project
@@ -66,6 +66,7 @@ dependencies {
dokka(project(":tree-structure-serialization"))
dokka(project(":tree-structure-coroutines"))
dokka(project(":tree-structure-compose"))
dokka(project(":tree-structure-immutable"))
}
dokka {

View File

@@ -6,6 +6,7 @@ binaryCompatibilityValidator = "0.16.3"
kover = "0.8.3"
coroutines = "1.9.0"
kotlinxSerialization = "1.7.3"
kotlinxCollectionsImmutable = "0.3.8"
composeMultiplatform = "1.7.3"
[plugins]
@@ -22,3 +23,4 @@ composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "k
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
kotlinx-collections-immutable = { module = "org.jetbrains.kotlinx:kotlinx-collections-immutable", version.ref = "kotlinxCollectionsImmutable" }

View File

@@ -3,3 +3,4 @@ rootProject.name = "tree-structure"
include(":tree-structure-serialization")
include(":tree-structure-coroutines")
include(":tree-structure-compose")
include(":tree-structure-immutable")

View File

@@ -61,6 +61,19 @@ public open class TreeNode<T>(public val value: T, public val treeIterator: Tree
* a cycle (i.e. [child] is this node or one of its ancestors).
*/
public fun addChild(child: TreeNode<T>) {
validateAttachable(child)
child._parent = this
_children.add(child)
}
/**
* Validates that [child] can be attached as a direct child of this node, throwing if it cannot.
*
* @param child the node about to be attached.
* @throws TreeNodeException if [child] already has a parent, or if attaching it here would create
* a cycle (i.e. [child] is this node or one of its ancestors).
*/
private fun validateAttachable(child: TreeNode<T>) {
if (child._parent != null) {
throw TreeNodeException("$child already has a parent; call detach() before re-attaching it.")
}
@@ -78,8 +91,6 @@ public open class TreeNode<T>(public val value: T, public val treeIterator: Tree
ancestor = ancestor._parent
}
}
child._parent = this
_children.add(child)
}
/**
@@ -118,6 +129,102 @@ public open class TreeNode<T>(public val value: T, public val treeIterator: Tree
return removed
}
/**
* Inserts [child] as a direct child of this node at the given [index], shifting any existing
* children at and after [index] one position to the right.
*
* @param index the position at which to insert [child]; must be in `0..children.size`.
* @param child a node that is not already attached to a tree. To move a node that already has a
* parent, call [detach] on it first.
* @throws IndexOutOfBoundsException if [index] is out of range.
* @throws TreeNodeException if [child] already has a parent, or if attaching it here would create
* a cycle (i.e. [child] is this node or one of its ancestors).
*/
public fun insertChild(index: Int, child: TreeNode<T>) {
validateAttachable(child)
child._parent = this
_children.add(index, child)
}
/**
* Removes the direct child at the given [index], detaching it (its parent becomes `null`).
*
* @param index the position of the child to remove; must be in `0 until children.size`.
* @return the detached child that was at [index].
* @throws IndexOutOfBoundsException if [index] is out of range.
*/
public fun removeChildAt(index: Int): TreeNode<T> {
val removed = _children.removeAt(index)
removed._parent = null
return removed
}
/**
* Replaces the direct child at the given [index] with [child], detaching the previous child
* (its parent becomes `null`).
*
* @param index the position of the child to replace; must be in `0 until children.size`.
* @param child a node that is not already attached to a tree. To move a node that already has a
* parent, call [detach] on it first.
* @return the previous child that was at [index], now detached.
* @throws IndexOutOfBoundsException if [index] is out of range.
* @throws TreeNodeException if [child] already has a parent, or if attaching it here would create
* a cycle (i.e. [child] is this node or one of its ancestors).
*/
public fun replaceChild(index: Int, child: TreeNode<T>): TreeNode<T> {
validateAttachable(child)
val old = _children[index]
old._parent = null
child._parent = this
_children[index] = child
return old
}
/**
* Moves an existing direct [child] to a new position within this node's [children].
*
* [toIndex] is coerced into the valid range, so out-of-range targets clamp to the first or last
* position. Because [child] is already a direct child, no re-parenting or cycle check is needed.
*
* @param child the node to reorder; must already be a direct child of this node.
* @param toIndex the target position for [child] after removal, coerced into `0..children.size`.
* @return `true` if [child] was a direct child and has been moved; `false` otherwise.
*/
public fun moveChild(child: TreeNode<T>, toIndex: Int): Boolean {
val from = _children.indexOf(child)
if (from < 0) return false
_children.removeAt(from)
_children.add(toIndex.coerceIn(0, _children.size), child)
return true
}
/**
* Adds each of [children] as a direct child of this node, in order, validating each one the same
* way as [addChild].
*
* Validation is performed per node as it is added, so if one node fails the children added before
* it remain attached (the same partial-application behaviour as calling [addChild] in a loop).
*
* @param children nodes that are not already attached to a tree.
* @throws TreeNodeException if any node already has a parent, or if attaching it here would create
* a cycle (i.e. it is this node or one of its ancestors).
*/
public fun addChildren(vararg children: TreeNode<T>) {
for (child in children) {
addChild(child)
}
}
/**
* Sorts this node's direct [children] in place according to the given [comparator]. Only the
* immediate children are reordered; their subtrees are left untouched.
*
* @param comparator the comparator used to order the children.
*/
public fun sortChildren(comparator: Comparator<TreeNode<T>>) {
_children.sortWith(comparator)
}
/**
* This function go through tree and counts children. Root element is not counted.
* @return All child and nested child count.

View File

@@ -0,0 +1,106 @@
package com.github.adriankuta.datastructure.tree
/**
* The four glyph strings used to draw the tree branches in [prettyString].
*
* Each value is the literal text emitted at the matching position:
* - [branch] precedes a child that is **not** its parent's last child.
* - [lastBranch] precedes a child that **is** its parent's last child.
* - [vertical] is accumulated into the prefix of the descendants of a non-last child (it keeps the
* vertical guide line going).
* - [empty] is accumulated into the prefix of the descendants of a last child (no guide line is
* needed past the last branch).
*
* Use [Default] for the box-drawing style or [Ascii] for a plain-ASCII style, or supply your own.
*
* @property branch drawn before a non-last child.
* @property vertical continuation prefix for descendants of a non-last child.
* @property lastBranch drawn before the last child.
* @property empty continuation prefix for descendants of a last child.
*/
public data class TreeConnectors(
public val branch: String,
public val vertical: String,
public val lastBranch: String,
public val empty: String,
) {
public companion object {
/** Box-drawing connectors, matching the output of the no-arg [TreeNode.prettyString]. */
public val Default: TreeConnectors = TreeConnectors(
branch = "├── ",
vertical = "",
lastBranch = "└── ",
empty = " ",
)
/** Plain-ASCII connectors for terminals or fonts that lack box-drawing glyphs. */
public val Ascii: TreeConnectors = TreeConnectors(
branch = "|-- ",
vertical = "| ",
lastBranch = "`-- ",
empty = " ",
)
}
}
/**
* Renders this subtree as a multi-line string, one node per line, with branch connectors.
*
* Calling this with all defaults produces output byte-identical to the no-arg member
* [TreeNode.prettyString]. Customise the drawing with [connectors] (e.g. [TreeConnectors.Ascii]) and
* the per-node text with [render].
*
* @param connectors the glyph set used to draw the branches. Defaults to [TreeConnectors.Default].
* @param render produces the text for each node from its `value`, its `depth` (distance from this
* receiver, which is `0`) and `isLast` (whether the node is its parent's last child; the root is
* considered `true`). Defaults to the value's string form (`"$value"`), which renders a `null`
* value as `"null"` to match the no-arg member.
* @return the rendered tree, each line terminated by `\n`.
*/
public fun <T> TreeNode<T>.prettyString(
connectors: TreeConnectors = TreeConnectors.Default,
render: (value: T, depth: Int, isLast: Boolean) -> String = { value, _, _ -> "$value" },
): String {
val stringBuilder = StringBuilder()
appendPretty(stringBuilder, "", "", 0, true, connectors, render)
return stringBuilder.toString()
}
private fun <T> TreeNode<T>.appendPretty(
stringBuilder: StringBuilder,
prefix: String,
childrenPrefix: String,
depth: Int,
isLast: Boolean,
connectors: TreeConnectors,
render: (value: T, depth: Int, isLast: Boolean) -> String,
) {
stringBuilder.append(prefix)
stringBuilder.append(render(value, depth, isLast))
stringBuilder.append('\n')
val childIterator = children.iterator()
while (childIterator.hasNext()) {
val node = childIterator.next()
if (childIterator.hasNext()) {
node.appendPretty(
stringBuilder,
childrenPrefix + connectors.branch,
childrenPrefix + connectors.vertical,
depth + 1,
false,
connectors,
render,
)
} else {
node.appendPretty(
stringBuilder,
childrenPrefix + connectors.lastBranch,
childrenPrefix + connectors.empty,
depth + 1,
true,
connectors,
render,
)
}
}
}

View File

@@ -0,0 +1,88 @@
package com.github.adriankuta.datastructure.tree
/**
* The lowest (deepest) node that is an ancestor of both this node and [other], where every node is
* considered an ancestor of itself.
*
* Nodes are compared by identity (`===`), so this only returns a node when both arguments live in
* the same tree.
*
* @param other the other node to find the common ancestor with.
* @return the lowest common ancestor, or `null` when the two nodes belong to different trees and
* therefore share no common ancestor.
*
* Runs in `O(da + db)` time and `O(da + db)` space, where `da`/`db` are the depths of the two nodes.
*/
public fun <T> TreeNode<T>.lowestCommonAncestor(other: TreeNode<T>): TreeNode<T>? {
// TreeNode has identity equality, so a HashSet gives O(1) identity membership and keeps the
// overall walk at O(da + db). Collect [other] and its ancestors, then climb from this node
// upward; the first node already on [other]'s chain is the deepest common ancestor.
val ancestorsOfOther = HashSet<TreeNode<T>>(other.ancestors())
ancestorsOfOther.add(other)
var node: TreeNode<T>? = this
while (node != null) {
if (node in ancestorsOfOther) return node
node = node.parent
}
return null
}
/**
* The number of edges on the shortest path between this node and [other].
*
* Computed as `depth() + other.depth() - 2 * lca.depth()`, where `lca` is their
* [lowestCommonAncestor]. The distance from a node to itself is `0`.
*
* @param other the other node to measure the distance to.
* @return the edge count, or `null` when the two nodes belong to different trees.
*
* Runs in `O(da + db)` time, where `da`/`db` are the depths of the two nodes.
*/
public fun <T> TreeNode<T>.distance(other: TreeNode<T>): Int? {
val lca = lowestCommonAncestor(other) ?: return null
return depth() + other.depth() - 2 * lca.depth()
}
/**
* The shortest path of nodes from this node to [other], inclusive of both endpoints.
*
* The path ascends from this node up to their [lowestCommonAncestor] and then descends to [other];
* the common ancestor appears exactly once. When `this === other` the result is `listOf(this)`. When
* one node is an ancestor of the other the path is simply the chain between them.
*
* @param other the node the path ends at.
* @return the path `[this, …, lca, …, other]`, or `null` when the two nodes belong to different
* trees.
*
* Runs in `O(da + db)` time and space, where `da`/`db` are the depths of the two nodes.
*/
public fun <T> TreeNode<T>.pathBetween(other: TreeNode<T>): List<TreeNode<T>>? {
val lca = lowestCommonAncestor(other) ?: return null
val up = mutableListOf<TreeNode<T>>()
var node: TreeNode<T> = this
up.add(node)
while (node !== lca) {
node = node.parent!!
up.add(node)
}
val down = mutableListOf<TreeNode<T>>()
node = other
down.add(node)
while (node !== lca) {
node = node.parent!!
down.add(node)
}
return up + down.dropLast(1).reversed()
}
/**
* Returns `true` when this subtree contains a node whose value equals [value], including the
* receiver itself. Values are compared with `==` ([equals]).
*
* @param value the value to search for.
* @return `true` if any node in the pre-order traversal of this subtree holds [value].
*
* Runs in `O(n)` time over the `n` nodes of this subtree and stops at the first match.
*/
public fun <T> TreeNode<T>.contains(value: T): Boolean =
preOrderSequence().any { it.value == value }

View File

@@ -0,0 +1,151 @@
package com.github.adriankuta.datastructure.tree
import com.github.adriankuta.datastructure.tree.exceptions.TreeNodeException
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
class TreeNodeMutationTest {
@Test
fun insertChildAtStartMiddleAndEnd() {
val root = TreeNode("root")
val a = TreeNode("a")
val b = TreeNode("b")
val c = TreeNode("c")
val d = TreeNode("d")
root.insertChild(0, b) // [b]
root.insertChild(0, a) // [a, b]
root.insertChild(2, d) // [a, b, d] (end)
root.insertChild(2, c) // [a, b, c, d] (middle)
assertContentEquals(listOf(a, b, c, d), root.children)
// Each inserted node is re-parented to root.
assertSame(root, a.parent)
assertSame(root, b.parent)
assertSame(root, c.parent)
assertSame(root, d.parent)
}
@Test
fun removeChildAtReturnsDetachedNodeAndClearsParent() {
val root = TreeNode("root")
val a = TreeNode("a")
val b = TreeNode("b")
val c = TreeNode("c")
root.addChildren(a, b, c)
val removed = root.removeChildAt(1)
assertSame(b, removed)
assertNull(removed.parent)
assertContentEquals(listOf(a, c), root.children)
}
@Test
fun replaceChildSwapsAndDetachesTheOld() {
val root = TreeNode("root")
val a = TreeNode("a")
val b = TreeNode("b")
val replacement = TreeNode("replacement")
root.addChildren(a, b)
val old = root.replaceChild(0, replacement)
assertSame(a, old)
assertNull(old.parent)
assertSame(root, replacement.parent)
assertContentEquals(listOf(replacement, b), root.children)
}
@Test
fun moveChildReordersChildren() {
val root = TreeNode("root")
val a = TreeNode("a")
val b = TreeNode("b")
val c = TreeNode("c")
root.addChildren(a, b, c)
assertTrue(root.moveChild(a, 2))
assertContentEquals(listOf(b, c, a), root.children)
// Parent pointer is unchanged after a move.
assertSame(root, a.parent)
}
@Test
fun moveChildReturnsFalseForNonChild() {
val root = TreeNode("root")
val a = TreeNode("a")
root.addChild(a)
val stranger = TreeNode("stranger")
assertFalse(root.moveChild(stranger, 0))
assertContentEquals(listOf(a), root.children)
}
@Test
fun addChildrenAppendsAllInOrder() {
val root = TreeNode("root")
val a = TreeNode("a")
val b = TreeNode("b")
val c = TreeNode("c")
root.addChildren(a, b, c)
assertContentEquals(listOf(a, b, c), root.children)
assertSame(root, a.parent)
assertSame(root, b.parent)
assertSame(root, c.parent)
}
@Test
fun addChildrenRejectsNodeThatAlreadyHasAParent() {
val root = TreeNode("root")
val attached = TreeNode("attached")
TreeNode("other").addChild(attached)
assertFailsWith<TreeNodeException> { root.addChildren(attached) }
}
@Test
fun insertChildRejectsNodeThatAlreadyHasAParent() {
val root = TreeNode("root")
val attached = TreeNode("attached")
TreeNode("other").addChild(attached)
assertFailsWith<TreeNodeException> { root.insertChild(0, attached) }
}
@Test
fun replaceChildRejectsNodeThatAlreadyHasAParent() {
val root = TreeNode("root")
val existing = TreeNode("existing")
root.addChild(existing)
val attached = TreeNode("attached")
TreeNode("other").addChild(attached)
assertFailsWith<TreeNodeException> { root.replaceChild(0, attached) }
// The original child is untouched after a failed replace.
assertContentEquals(listOf(existing), root.children)
assertSame(root, existing.parent)
}
@Test
fun sortChildrenReordersByComparator() {
val root = TreeNode("root")
val c = TreeNode("c")
val a = TreeNode("a")
val b = TreeNode("b")
root.addChildren(c, a, b)
root.sortChildren(compareBy { it.value })
assertContentEquals(listOf(a, b, c), root.children)
}
}

View File

@@ -0,0 +1,100 @@
package com.github.adriankuta.datastructure.tree
import kotlin.test.Test
import kotlin.test.assertEquals
class TreeNodePrettyPrintTest {
private fun sampleTree(): TreeNode<String> {
val root = TreeNode("Root")
val beverages = TreeNode("Beverages")
val curd = TreeNode("Curd")
root.addChild(beverages)
root.addChild(curd)
val tea = TreeNode("tea")
val coffee = TreeNode("coffee")
beverages.addChild(tea)
beverages.addChild(coffee)
tea.addChild(TreeNode("ginger tea"))
tea.addChild(TreeNode("normal tea"))
curd.addChild(TreeNode("yogurt"))
curd.addChild(TreeNode("lassi"))
return root
}
@Test
fun defaultConnectorsMatchMemberPrettyString() {
val root = sampleTree()
assertEquals(root.prettyString(), root.prettyString(connectors = TreeConnectors.Default))
}
@Test
fun defaultRenderMatchesMemberForNullValues() {
// The member prettyString() appends the value via StringBuilder, rendering null as "null".
// The all-defaults extension must stay byte-identical, including for null-valued nodes.
val root = TreeNode<String?>(null)
root.addChild(TreeNode("child"))
root.addChild(TreeNode<String?>(null))
assertEquals(root.prettyString(), root.prettyString(connectors = TreeConnectors.Default))
assertEquals(
"null\n" +
"├── child\n" +
"└── null\n",
root.prettyString(),
)
}
@Test
fun asciiConnectorsRenderPlainAscii() {
val root = sampleTree()
assertEquals(
"Root\n" +
"|-- Beverages\n" +
"| |-- tea\n" +
"| | |-- ginger tea\n" +
"| | `-- normal tea\n" +
"| `-- coffee\n" +
"`-- Curd\n" +
" |-- yogurt\n" +
" `-- lassi\n",
root.prettyString(connectors = TreeConnectors.Ascii),
)
}
@Test
fun customRenderIsApplied() {
val root = sampleTree()
assertEquals(
"ROOT\n" +
"├── BEVERAGES\n" +
"│ ├── TEA\n" +
"│ │ ├── GINGER TEA\n" +
"│ │ └── NORMAL TEA\n" +
"│ └── COFFEE\n" +
"└── CURD\n" +
" ├── YOGURT\n" +
" └── LASSI\n",
root.prettyString { value, _, _ -> value.uppercase() },
)
}
@Test
fun depthAndIsLastArePassedToRender() {
val root = sampleTree()
assertEquals(
"Root depth=0 last=true\n" +
"├── Beverages depth=1 last=false\n" +
"│ ├── tea depth=2 last=false\n" +
"│ │ ├── ginger tea depth=3 last=false\n" +
"│ │ └── normal tea depth=3 last=true\n" +
"│ └── coffee depth=2 last=true\n" +
"└── Curd depth=1 last=true\n" +
" ├── yogurt depth=2 last=false\n" +
" └── lassi depth=2 last=true\n",
root.prettyString { value, depth, isLast -> "$value depth=$depth last=$isLast" },
)
}
}

View File

@@ -0,0 +1,123 @@
package com.github.adriankuta.datastructure.tree
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
class TreeNodeQueryTest {
// root(1)
// ├── n2(2)
// │ ├── n4(4)
// │ └── n5(5)
// └── n3(3)
// └── n6(6)
private val root = TreeNode(1)
private val n2 = TreeNode(2)
private val n3 = TreeNode(3)
private val n4 = TreeNode(4)
private val n5 = TreeNode(5)
private val n6 = TreeNode(6)
// A completely separate tree.
private val otherRoot = TreeNode(10)
private val o11 = TreeNode(11)
init {
root.addChild(n2)
root.addChild(n3)
n2.addChild(n4)
n2.addChild(n5)
n3.addChild(n6)
otherRoot.addChild(o11)
}
@Test
fun lowestCommonAncestorOfTwoLeaves() {
assertSame(n2, n4.lowestCommonAncestor(n5))
assertSame(root, n4.lowestCommonAncestor(n6))
}
@Test
fun lowestCommonAncestorOfSameNode() {
assertSame(n4, n4.lowestCommonAncestor(n4))
}
@Test
fun lowestCommonAncestorOfAncestorAndDescendant() {
assertSame(n2, n2.lowestCommonAncestor(n4))
assertSame(n2, n4.lowestCommonAncestor(n2))
assertSame(root, root.lowestCommonAncestor(n6))
}
@Test
fun lowestCommonAncestorOfNodesInDifferentTreesIsNull() {
assertNull(n4.lowestCommonAncestor(o11))
assertNull(o11.lowestCommonAncestor(n4))
}
@Test
fun distanceValues() {
assertEquals(0, n4.distance(n4))
assertEquals(2, n4.distance(n5))
assertEquals(1, n2.distance(n4))
assertEquals(4, n4.distance(n6))
assertEquals(2, root.distance(n4))
}
@Test
fun distanceOfNodesInDifferentTreesIsNull() {
assertNull(n4.distance(o11))
}
@Test
fun pathBetweenSameNode() {
assertContentEquals(listOf(n4), n4.pathBetween(n4))
}
@Test
fun pathBetweenTwoLeaves() {
// n4 -> n2 -> n5 (lca = n2 appears once, endpoints are n4 and n5)
assertContentEquals(listOf(n4, n2, n5), n4.pathBetween(n5))
// n4 -> n2 -> root -> n3 -> n6 (lca = root appears once)
assertContentEquals(listOf(n4, n2, root, n3, n6), n4.pathBetween(n6))
}
@Test
fun pathBetweenWithUnequalDepthLegs() {
// Neither is an ancestor of the other and the legs differ in length: n4 is at depth 2, n3 at
// depth 1, lca = root. Exercises the asymmetric up/down assembly.
assertContentEquals(listOf(n4, n2, root, n3), n4.pathBetween(n3))
assertContentEquals(listOf(n3, root, n2, n4), n3.pathBetween(n4))
}
@Test
fun pathBetweenAncestorAndDescendant() {
assertContentEquals(listOf(n2, n4), n2.pathBetween(n4))
assertContentEquals(listOf(n4, n2), n4.pathBetween(n2))
assertContentEquals(listOf(root, n3, n6), root.pathBetween(n6))
}
@Test
fun pathBetweenOfNodesInDifferentTreesIsNull() {
assertNull(n4.pathBetween(o11))
}
@Test
fun containsTrueForValuesInSubtree() {
assertTrue(root.contains(1)) // the receiver itself
assertTrue(root.contains(6))
assertTrue(n2.contains(5))
}
@Test
fun containsFalseForValuesNotInSubtree() {
assertFalse(n2.contains(6)) // n6 lives under n3, not n2
assertFalse(root.contains(99))
}
}

View File

@@ -0,0 +1,25 @@
public final class com/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode {
public fun <init> (Ljava/lang/Object;Lkotlinx/collections/immutable/PersistentList;)V
public synthetic fun <init> (Ljava/lang/Object;Lkotlinx/collections/immutable/PersistentList;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public final fun addChild (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;)Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;
public final fun component1 ()Ljava/lang/Object;
public final fun component2 ()Lkotlinx/collections/immutable/PersistentList;
public final fun copy (Ljava/lang/Object;Lkotlinx/collections/immutable/PersistentList;)Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;
public static synthetic fun copy$default (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;Ljava/lang/Object;Lkotlinx/collections/immutable/PersistentList;ILjava/lang/Object;)Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;
public fun equals (Ljava/lang/Object;)Z
public final fun getChildren ()Lkotlinx/collections/immutable/PersistentList;
public final fun getValue ()Ljava/lang/Object;
public fun hashCode ()I
public final fun mapValues (Lkotlin/jvm/functions/Function1;)Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;
public final fun removeChild (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;)Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;
public fun toString ()Ljava/lang/String;
}
public final class com/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNodeKt {
public static final fun height (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;)I
public static final fun levelOrder (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;)Ljava/util/List;
public static final fun nodeCount (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;)I
public static final fun postOrder (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;)Ljava/util/List;
public static final fun preOrder (Lcom/github/adriankuta/datastructure/tree/immutable/ImmutableTreeNode;)Ljava/util/List;
}

View File

@@ -0,0 +1,101 @@
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.dokka)
alias(libs.plugins.mavenPublish)
signing
}
group = "com.github.adriankuta"
version = rootProject.version
mavenPublishing {
publishToMavenCentral(automaticRelease = false)
signAllPublications()
coordinates("com.github.adriankuta", "tree-structure-immutable", version.toString())
pom {
name.set("Tree Data Structure — immutable")
description.set("Immutable, persistent tree variant (ImmutableTreeNode with structural sharing) for the tree-structure library.")
url.set("https://github.com/AdrianKuta/Tree-Data-Structure")
licenses {
license {
name.set("MIT License")
url.set("https://opensource.org/licenses/MIT")
distribution.set("repo")
}
}
developers {
developer {
id.set("AdrianKuta")
name.set("Adrian Kuta")
email.set("adrian.kuta93@gmail.com")
}
}
scm {
url.set("https://github.com/AdrianKuta/Tree-Data-Structure")
connection.set("scm:git:https://github.com/AdrianKuta/Tree-Data-Structure.git")
developerConnection.set("scm:git:ssh://git@github.com/AdrianKuta/Tree-Data-Structure.git")
}
}
}
repositories {
mavenCentral()
}
dokka {
dokkaSourceSets.configureEach {
sourceLink {
// Resolve this module's GitHub source path relative to the repo root.
localDirectory.set(projectDir.resolve("src"))
val module = projectDir.relativeTo(rootDir).invariantSeparatorsPath
val prefix = if (module.isEmpty()) "" else "$module/"
remoteUrl("https://github.com/AdrianKuta/Tree-Data-Structure/blob/master/${prefix}src")
remoteLineSuffix.set("#L")
}
}
}
kotlin {
explicitApi()
jvmToolchain(21)
jvm()
js(IR) {
browser()
nodejs()
}
@OptIn(ExperimentalWasmDsl::class)
wasmJs {
browser()
nodejs()
}
iosX64()
iosArm64()
iosSimulatorArm64()
val hostOs = System.getProperty("os.name")
val isMingwX64 = hostOs.startsWith("Windows")
when {
hostOs == "Mac OS X" -> macosX64("native")
hostOs == "Linux" -> linuxX64("native")
isMingwX64 -> mingwX64("native")
else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
}
sourceSets {
commonMain.dependencies {
api(project(":"))
implementation(libs.kotlinx.collections.immutable)
}
commonTest.dependencies {
implementation(kotlin("test"))
}
}
}

View File

@@ -0,0 +1,147 @@
package com.github.adriankuta.datastructure.tree.immutable
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList
/**
* A node in an immutable, persistent n-ary tree. Each node holds a [value] and an ordered
* [PersistentList] of [children]; nodes never carry a parent back-reference, so a subtree is a
* self-contained, acyclic value.
*
* Every mutating operation ([addChild], [removeChild], [mapValues]) returns a **new** root and
* leaves the receiver untouched. Subtrees that are not on the path of the change are reused as the
* same instances (structural sharing), so updates are cheap and old roots stay valid.
*
* Equality is value-based: two nodes are equal when their [value]s and [children] are equal
* (a `data class`), independent of identity.
*
* @param value the value stored in this node.
* @param children the ordered, persistent list of child subtrees.
*/
public data class ImmutableTreeNode<T>(
public val value: T,
public val children: PersistentList<ImmutableTreeNode<T>> = persistentListOf(),
) {
/**
* Returns a new node with [child] appended to this node's [children]. The receiver and every
* existing child subtree are reused unchanged (structural sharing).
*
* @param child the subtree to append.
* @return a new [ImmutableTreeNode] with [child] added; the receiver is not modified.
*/
public fun addChild(child: ImmutableTreeNode<T>): ImmutableTreeNode<T> =
copy(children = children.add(child))
/**
* Returns a new node with the first occurrence of [child] removed from this node's direct
* [children], compared by value-based equality. If [child] is not a direct child, a structurally
* equal new node is returned. The receiver is never modified.
*
* @param child the direct child subtree to remove.
* @return a new [ImmutableTreeNode] without [child]; the receiver is not modified.
*/
public fun removeChild(child: ImmutableTreeNode<T>): ImmutableTreeNode<T> =
copy(children = children.remove(child))
/**
* Returns a new tree of the same shape with every node's value transformed by [transform].
* The receiver is not modified.
*
* @param transform maps each node's value of type [T] to a value of type [R].
* @return a new [ImmutableTreeNode] of type [R] mirroring this tree's structure.
*/
public fun <R> mapValues(transform: (T) -> R): ImmutableTreeNode<R> =
ImmutableTreeNode(transform(value), children.map { it.mapValues(transform) }.toPersistentList())
}
/**
* Returns this subtree's nodes in pre-order (the receiver first, then each child subtree in order).
* Implemented iteratively, so it is safe on arbitrarily deep trees.
*
* @return the nodes of this subtree in pre-order, starting with the receiver.
*/
public fun <T> ImmutableTreeNode<T>.preOrder(): List<ImmutableTreeNode<T>> {
val result = mutableListOf<ImmutableTreeNode<T>>()
val stack = ArrayDeque<ImmutableTreeNode<T>>()
stack.addLast(this)
while (stack.isNotEmpty()) {
val node = stack.removeLast()
result.add(node)
node.children.asReversed().forEach { stack.addLast(it) }
}
return result
}
/**
* Returns this subtree's nodes in post-order (each child subtree in order, then the receiver last).
* Implemented iteratively, so it is safe on arbitrarily deep trees.
*
* @return the nodes of this subtree in post-order, ending with the receiver.
*/
public fun <T> ImmutableTreeNode<T>.postOrder(): List<ImmutableTreeNode<T>> {
val result = ArrayDeque<ImmutableTreeNode<T>>()
val stack = ArrayDeque<ImmutableTreeNode<T>>()
stack.addLast(this)
while (stack.isNotEmpty()) {
val node = stack.removeLast()
result.addFirst(node)
node.children.forEach { stack.addLast(it) }
}
return result.toList()
}
/**
* Returns this subtree's nodes in level-order (breadth-first: the receiver, then its children, then
* their children, and so on). Implemented iteratively, so it is safe on arbitrarily deep trees.
*
* @return the nodes of this subtree in breadth-first order, starting with the receiver.
*/
public fun <T> ImmutableTreeNode<T>.levelOrder(): List<ImmutableTreeNode<T>> {
val result = mutableListOf<ImmutableTreeNode<T>>()
val queue = ArrayDeque<ImmutableTreeNode<T>>()
queue.addLast(this)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
result.add(node)
node.children.forEach { queue.addLast(it) }
}
return result
}
/**
* Counts all descendants of this node; the receiver itself is not counted (matching the core
* `TreeNode.nodeCount`). Implemented iteratively, so it is safe on arbitrarily deep trees.
*
* @return the number of descendant nodes (children and nested children) of this node.
*/
public fun <T> ImmutableTreeNode<T>.nodeCount(): Int {
var count = 0
val stack = ArrayDeque<ImmutableTreeNode<T>>()
stack.addAll(children)
while (stack.isNotEmpty()) {
val node = stack.removeLast()
count++
stack.addAll(node.children)
}
return count
}
/**
* Returns the number of edges on the longest path between this node and a descendant leaf (0 for a
* leaf). Implemented iteratively, so it is safe on arbitrarily deep trees.
*
* @return the height of this subtree, measured in edges.
*/
public fun <T> ImmutableTreeNode<T>.height(): Int {
var maxDepth = 0
val stack = ArrayDeque<Pair<ImmutableTreeNode<T>, Int>>()
stack.addLast(this to 0)
while (stack.isNotEmpty()) {
val (node, depthSoFar) = stack.removeLast()
if (depthSoFar > maxDepth) maxDepth = depthSoFar
node.children.forEach { stack.addLast(it to depthSoFar + 1) }
}
return maxDepth
}

View File

@@ -0,0 +1,135 @@
package com.github.adriankuta.datastructure.tree.immutable
import kotlinx.collections.immutable.persistentListOf
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertSame
import kotlin.test.assertTrue
class ImmutableTreeNodeTest {
// World
// ├── North America
// │ └── USA
// └── Europe
// ├── Poland
// └── Germany
private val usa = ImmutableTreeNode("USA")
private val northAmerica = ImmutableTreeNode("North America", persistentListOf(usa))
private val poland = ImmutableTreeNode("Poland")
private val germany = ImmutableTreeNode("Germany")
private val europe = ImmutableTreeNode("Europe", persistentListOf(poland, germany))
private val world = ImmutableTreeNode("World", persistentListOf(northAmerica, europe))
@Test
fun addChildReturnsNewInstanceAndLeavesOriginalUnchanged() {
val asia = ImmutableTreeNode("Asia")
val updated = world.addChild(asia)
assertEquals(3, updated.children.size)
assertEquals("Asia", updated.children[2].value)
// Original is untouched.
assertEquals(2, world.children.size)
assertFalse(updated === world)
}
@Test
fun removeChildReturnsNewInstanceAndLeavesOriginalUnchanged() {
val updated = world.removeChild(europe)
assertEquals(1, updated.children.size)
assertEquals("North America", updated.children[0].value)
// Original is untouched.
assertEquals(2, world.children.size)
assertFalse(updated === world)
}
@Test
fun addChildSharesUnmodifiedSiblingSubtrees() {
val asia = ImmutableTreeNode("Asia")
val updated = world.addChild(asia)
// The siblings that are not on the modified path are the SAME instances.
assertSame(northAmerica, updated.children[0])
assertSame(europe, updated.children[1])
}
@Test
fun rebuildingOnlyOnePathSharesTheOtherSubtree() {
// Add a child under Europe; North America's subtree should be reused untouched.
val spain = ImmutableTreeNode("Spain")
val newEurope = europe.addChild(spain)
val updated = world.copy(children = world.children.set(1, newEurope))
assertSame(northAmerica, updated.children[0])
assertFalse(updated.children[1] === europe)
assertSame(usa, updated.children[0].children[0])
}
@Test
fun mapValuesTransformsEveryValueAndKeepsShape() {
val lengths = world.mapValues { it.length }
assertEquals("World".length, lengths.value)
assertEquals(2, lengths.children.size)
assertEquals("North America".length, lengths.children[0].value)
assertEquals("USA".length, lengths.children[0].children[0].value)
assertEquals("Germany".length, lengths.children[1].children[1].value)
}
@Test
fun preOrderVisitsParentBeforeChildren() {
assertEquals(
listOf("World", "North America", "USA", "Europe", "Poland", "Germany"),
world.preOrder().map { it.value },
)
}
@Test
fun postOrderVisitsChildrenBeforeParent() {
assertEquals(
listOf("USA", "North America", "Poland", "Germany", "Europe", "World"),
world.postOrder().map { it.value },
)
}
@Test
fun levelOrderVisitsBreadthFirst() {
assertEquals(
listOf("World", "North America", "Europe", "USA", "Poland", "Germany"),
world.levelOrder().map { it.value },
)
}
@Test
fun nodeCountExcludesReceiver() {
assertEquals(5, world.nodeCount())
assertEquals(1, northAmerica.nodeCount())
assertEquals(0, usa.nodeCount())
}
@Test
fun heightCountsEdgesOnLongestPath() {
assertEquals(2, world.height())
assertEquals(1, europe.height())
assertEquals(0, usa.height())
}
@Test
fun equalityIsValueBased() {
val sameWorld = ImmutableTreeNode(
"World",
persistentListOf(
ImmutableTreeNode("North America", persistentListOf(ImmutableTreeNode("USA"))),
ImmutableTreeNode("Europe", persistentListOf(ImmutableTreeNode("Poland"), ImmutableTreeNode("Germany"))),
),
)
assertEquals(world, sameWorld)
assertTrue(world == sameWorld)
assertFalse(world === sameWorld)
}
}