7 Commits

Author SHA1 Message Date
Adrian Kuta
0fe6535258 Release 4.2.0
Some checks failed
Test / JVM / JS / Wasm / Native / Android + API check (push) Has been cancelled
Test / iOS (push) Has been cancelled
- PUBLISH_VERSION 4.1.1 -> 4.2.0
- CHANGELOG: promote [Unreleased] -> [4.2.0] (2026-06-08) + compare link
- README: bump install snippets to 4.2.0

Adds the Android target for tree-structure and tree-structure-compose,
the default TreeNodeRow composable + LazyTree(label=...) overload, and a
runnable Android sample. All additive, no breaking changes.
2026-06-08 21:58:23 +02:00
Adrian Kuta
28c1690f96 fix: raise Gradle daemon heap/Metaspace for the Android (AGP) build
The Android target added in #48 brought AGP onto the build's classpath
without setting org.gradle.jvmargs, so the Gradle daemon ran on its
defaults (512m heap / 384m Metaspace). AGP loads enough classes that,
combined with the KMP matrix, binary-compatibility-validator, Kover and
Dokka in a single build, the daemon exhausts Metaspace and is killed
mid-build (GC thrashing / out of Metaspace). The
'JVM / JS / Wasm / Native / Android + API check' job therefore failed
deterministically on master, and the publish job builds the same targets.

Set org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g. Verified with a
cold full-matrix build locally.
2026-06-08 21:58:23 +02:00
Adrian Kuta
dc59476b10 feat: add Android target and default TreeNodeRow to tree-structure-compose (#39) (#48)
Add the `android` target to the Compose Multiplatform library and a sensible
default renderer, so the largest Compose audience is a first-class consumer.

- Core `tree-structure` and `tree-structure-compose` now build and publish an
  `-android` variant (compileSdk 35, minSdk 21). The core needs it too: its
  inline `tree { }` DSL is built per target, and Android consumers (JVM 11/17)
  cannot inline a JVM-21 build.
- `TreeNodeRow`: a foundation-only default node row (clickable, indented, with a
  `▾`/`▸` marker, no Material dependency), plus a no-content `LazyTree(root,
  label = …)` overload that uses it. The existing lambda overload is unchanged.
- New `samples` Android app module demonstrating `LazyTree` + `@Preview`
  (not published; excluded from API validation).
- Toolchain: Gradle wrapper 8.5 -> 8.10.2, Android Gradle Plugin 8.7.2.
- binary-compatibility-validator now emits per-target dumps (api/jvm, api/android)
  for the two multi-JVM-target modules; CI assembles the Android outputs.
2026-06-08 19:43:05 +00:00
Adrian Kuta
1fce412815 feat: add runnable :samples module (#47)
Some checks failed
Test / JVM / JS / Wasm / Native + API check (push) Has been cancelled
Test / iOS (push) Has been cancelled
* build: scaffold :samples module (issue #37)

* feat: add runnable, verified examples to :samples (issue #37)

* ci,docs: run :samples in CI and document ./gradlew :samples:run (issue #37)
2026-06-08 13:59:16 +02:00
Adrian Kuta
2671c46f96 test: property-based tests for traversal & structural invariants (#38) (#46)
Add TreeNodePropertyTest: 23 properties checked over many seeded, randomly
generated trees instead of fixed examples. Covers the invariants from #38 —
all three orders visit the same node set with matching cardinality; pre/post
emit each subtree as a contiguous block; level-order is depth-monotonic;
child.depth == parent.depth + 1 (cross-checked against an independent BFS
level walk); nodeCount stays consistent across attach/detach, remove/insert
and clear; and every traversal terminates and is correctly ordered on deep
(5k-node chain) and wide (5k-child) trees. Also pins parent/child pointer
consistency, ancestor/leaf/sibling correctness, deepCopy/mapValues shape
preservation, and lca/distance/pathBetween.

The generator builds trees by uniform random attachment (iterative, so it is
stack-safe and free of left-heavy skew). Failures print the seed, so any case
reproduces. No new dependency — the suite is pure commonTest and runs on every
target (JVM/JS/Wasm/Native).
2026-06-08 13:29:30 +02:00
Adrian Kuta
f1e9a7bb54 chore: gitignore local superpowers working docs (docs/superpowers/) 2026-06-08 08:55:04 +02:00
Adrian Kuta
a7d5de1bba docs: remove design spec accidentally committed in v4.1.1 release 2026-06-08 08:53:12 +02:00
25 changed files with 1178 additions and 97 deletions

View File

@@ -21,9 +21,9 @@ jobs:
fail-fast: false
matrix:
include:
- name: JVM / JS / Wasm / Native + API check
- name: JVM / JS / Wasm / Native / Android + API check
os: ubuntu-latest
tasks: jvmTest jsNodeTest wasmJsNodeTest nativeTest apiCheck
tasks: jvmTest jsNodeTest wasmJsNodeTest nativeTest :assembleRelease :tree-structure-compose:assembleRelease :samples-android:assembleDebug :samples:test :samples:run apiCheck
- name: iOS
os: macos-latest
tasks: iosSimulatorArm64Test

3
.gitignore vendored
View File

@@ -19,3 +19,6 @@ build/
/.idea/jarRepositories.xml
/.idea/deploymentTargetDropDown.xml
/.idea/
# Local superpowers working docs (design specs, plans) — not part of the repo
docs/superpowers/

View File

@@ -4,7 +4,20 @@ All notable changes to this project are documented here. The format is based on
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [4.2.0] - 2026-06-08
### Added
- **Android target.** The core `tree-structure` module and `tree-structure-compose` now publish an
`-android` variant (`minSdk` 21), so both can be consumed directly in Android projects.
- `tree-structure-compose`: a foundation-only `TreeNodeRow` composable — a sensible default node row
(clickable, indented, with a `▾`/`▸` marker and no Material dependency) — plus a no-content
`LazyTree(root, label = …)` overload that renders each node with it. The existing lambda overload
is unchanged.
- A runnable Android sample app in the new `samples` module, with `@Preview` composables.
### Changed
- Upgraded the Gradle wrapper to 8.10.2 and introduced Android Gradle Plugin 8.7.2 (`compileSdk` 35).
No source or behavior changes to existing targets.
## [4.1.1] - 2026-06-08
@@ -99,7 +112,7 @@ 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.1.1...HEAD
[4.2.0]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v4.1.1...v4.2.0
[4.1.1]: https://github.com/AdrianKuta/Tree-Data-Structure/compare/v4.1.0...v4.1.1
[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

View File

@@ -16,7 +16,7 @@ usually a better fit.
## Features
- Kotlin Multiplatform: JVM, JS, Wasm, iOS, and a native host target.
- Kotlin Multiplatform: JVM, Android, JS, Wasm, iOS, and a native host target.
- Build trees with a `tree { child(...) }` DSL or node by node with `addChild`.
- Pre-order, post-order, and level-order traversal, as iterators or lazy `Sequence`s.
- Navigation: `root()`, `ancestors()`, `siblings()`, `leaves()`, `descendants()`, `isLeaf`, `degree`.
@@ -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.1.1") // latest version is on the badge above
implementation("com.github.adriankuta:tree-structure:4.2.0") // latest version is on the badge above
}
```
Gradle (Groovy):
```groovy
dependencies {
implementation "com.github.adriankuta:tree-structure:4.1.1"
implementation "com.github.adriankuta:tree-structure:4.2.0"
}
```
@@ -46,7 +46,7 @@ Maven:
<dependency>
<groupId>com.github.adriankuta</groupId>
<artifactId>tree-structure</artifactId>
<version>4.1.1</version>
<version>4.2.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.1.1")
implementation("com.github.adriankuta:tree-structure-serialization:4.2.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.1.1")
implementation("com.github.adriankuta:tree-structure-coroutines:4.2.0")
```
```kotlin
root.preOrderFlow().collect { println(it.value) }
@@ -181,12 +181,23 @@ root.asFlow(TreeNodeIterators.LevelOrder).map { it.value }
### Compose UI (`tree-structure-compose`)
A `LazyTree` composable for Compose Multiplatform (JVM/desktop, iOS, Wasm). Only the visible nodes
are composed, and you decide how each node looks:
A `LazyTree` composable for Compose Multiplatform (JVM/desktop, Android, iOS, Wasm). Only the visible
nodes are composed.
```kotlin
implementation("com.github.adriankuta:tree-structure-compose:4.1.1")
implementation("com.github.adriankuta:tree-structure-compose:4.2.0")
```
For the common case, the no-content overload renders each node with the built-in `TreeNodeRow`
(a clickable, indented row with a `▾`/`▸` marker — foundation-only, no Material dependency):
```kotlin
LazyTree(root) // sensible default
LazyTree(root, label = { it.name }) // map a node's value to its text
```
Or supply your own row for full control:
```kotlin
LazyTree(root) { node, depth, expanded, toggle ->
Row(Modifier.padding(start = (depth * 16).dp).clickable(onClick = toggle)) {
@@ -196,6 +207,8 @@ LazyTree(root) { node, depth, expanded, toggle ->
}
```
A runnable Android demo lives in the [`samples-android`](samples-android) module.
### Immutable (`tree-structure-immutable`)
A persistent `ImmutableTreeNode` with structural sharing. Every operation (`addChild`,
@@ -204,7 +217,7 @@ 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.1")
implementation("com.github.adriankuta:tree-structure-immutable:4.2.0")
```
```kotlin
val root = ImmutableTreeNode("World").addChild(ImmutableTreeNode("Europe"))
@@ -213,6 +226,15 @@ val bigger = root.addChild(ImmutableTreeNode("Asia")) // root is unchanged; bigg
bigger.preOrder().forEach { println(it.value) } // pre/post/level-order, nodeCount(), height()
```
## Examples
A runnable `:samples` module bundles compile-checked, assertion-verified examples of the core API
and the serialization, coroutines, and immutable modules. Run them with:
```
./gradlew :samples:run
```
## Notes
`TreeNode` is mutable and not thread-safe. Add your own synchronization if you share a tree across

142
api/jvm/tree-structure.api Normal file
View File

@@ -0,0 +1,142 @@
public abstract interface class com/github/adriankuta/datastructure/tree/ChildDeclarationInterface {
public abstract synthetic fun child (Ljava/lang/Object;Lkotlin/jvm/functions/Function1;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
}
public final class com/github/adriankuta/datastructure/tree/ChildDeclarationInterface$DefaultImpls {
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
public final fun detach ()Z
public final fun getChildren ()Ljava/util/List;
public final fun getParent ()Lcom/github/adriankuta/datastructure/tree/TreeNode;
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;
}
public final class com/github/adriankuta/datastructure/tree/TreeNodeFunctionalExtKt {
public static final fun allNodes (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lkotlin/jvm/functions/Function1;)Z
public static final fun anyNode (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lkotlin/jvm/functions/Function1;)Z
public static final fun countNodes (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lkotlin/jvm/functions/Function1;)I
public static final fun deepCopy (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
public static final fun filterNodes (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lkotlin/jvm/functions/Function1;)Ljava/util/List;
public static final fun findNode (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lkotlin/jvm/functions/Function1;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
public static final fun foldNodes (Lcom/github/adriankuta/datastructure/tree/TreeNode;Ljava/lang/Object;Lkotlin/jvm/functions/Function2;)Ljava/lang/Object;
public static final fun mapValues (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lkotlin/jvm/functions/Function1;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
public static final fun structurallyEquals (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/TreeNode;)Z
}
public final class com/github/adriankuta/datastructure/tree/TreeNodeNavigationExtKt {
public static final fun ancestors (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Ljava/util/List;
public static final fun descendants (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Ljava/util/List;
public static final fun getDegree (Lcom/github/adriankuta/datastructure/tree/TreeNode;)I
public static final fun isLeaf (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Z
public static final fun leaves (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Ljava/util/List;
public static final fun root (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
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;
public static final fun levelOrderSequence (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lkotlin/sequences/Sequence;
public static final fun postOrderSequence (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lkotlin/sequences/Sequence;
public static final fun preOrderSequence (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lkotlin/sequences/Sequence;
}
public final class com/github/adriankuta/datastructure/tree/exceptions/TreeNodeException : java/lang/RuntimeException {
public fun <init> ()V
public fun <init> (Ljava/lang/String;)V
public fun <init> (Ljava/lang/String;Ljava/lang/Throwable;)V
public synthetic fun <init> (Ljava/lang/String;Ljava/lang/Throwable;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
}
public final class com/github/adriankuta/datastructure/tree/iterators/LevelOrderTreeIterator : java/util/Iterator, kotlin/jvm/internal/markers/KMappedMarker {
public fun <init> (Lcom/github/adriankuta/datastructure/tree/TreeNode;)V
public fun hasNext ()Z
public fun next ()Lcom/github/adriankuta/datastructure/tree/TreeNode;
public synthetic fun next ()Ljava/lang/Object;
public fun remove ()V
}
public final class com/github/adriankuta/datastructure/tree/iterators/PostOrderTreeIterator : java/util/Iterator, kotlin/jvm/internal/markers/KMappedMarker {
public fun <init> (Lcom/github/adriankuta/datastructure/tree/TreeNode;)V
public fun hasNext ()Z
public fun next ()Lcom/github/adriankuta/datastructure/tree/TreeNode;
public synthetic fun next ()Ljava/lang/Object;
public fun remove ()V
}
public final class com/github/adriankuta/datastructure/tree/iterators/PreOrderTreeIterator : java/util/Iterator, kotlin/jvm/internal/markers/KMappedMarker {
public fun <init> (Lcom/github/adriankuta/datastructure/tree/TreeNode;)V
public fun hasNext ()Z
public fun next ()Lcom/github/adriankuta/datastructure/tree/TreeNode;
public synthetic fun next ()Ljava/lang/Object;
public fun remove ()V
}
public final class com/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators : java/lang/Enum {
public static final field LevelOrder Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;
public static final field PostOrder Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;
public static final field PreOrder Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;
public static fun getEntries ()Lkotlin/enums/EnumEntries;
public static fun valueOf (Ljava/lang/String;)Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;
public static fun values ()[Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;
}

View File

@@ -7,11 +7,16 @@ plugins {
alias(libs.plugins.binaryCompatibilityValidator)
alias(libs.plugins.kover)
signing
alias(libs.plugins.androidLibrary)
// Loaded once here (with a known version) so the Android application/library variants can be
// applied across subprojects without the "already on the classpath with an unknown version" clash.
alias(libs.plugins.androidApplication) apply false
alias(libs.plugins.kotlinAndroid) apply false
}
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.1.1"
val PUBLISH_VERSION = "4.2.0"
val snapshot: String? by project
@@ -57,6 +62,13 @@ mavenPublishing {
repositories {
mavenCentral()
google()
}
apiValidation {
// Neither sample module is a published artifact, so neither has a .api dump.
ignoredProjects.add("samples")
ignoredProjects.add("samples-android")
}
dependencies {
@@ -89,6 +101,15 @@ kotlin {
jvm()
androidTarget {
publishLibraryVariants("release")
// Build the Android variant at JVM 17 so Android consumers (JVM 11/17) can inline the
// library's inline DSL (`tree { }`) — they cannot inline the default JVM-21 bytecode.
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
js(IR) {
browser()
nodejs()
@@ -121,3 +142,15 @@ kotlin {
}
}
}
android {
namespace = "com.github.adriankuta.datastructure.tree"
compileSdk = libs.versions.androidCompileSdk.get().toInt()
defaultConfig {
minSdk = libs.versions.androidMinSdk.get().toInt()
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}

View File

@@ -1,77 +0,0 @@
# Design — four additive enhancements to `tree-structure` (target 4.1.0)
Date: 2026-06-07. Source issues: #34, #35, #36, #33. Integration: **four separate PRs**,
one per issue (`Closes #NN`), matching the repo's per-issue PR convention (#32).
## Shared rules (every issue)
- `explicitApi()` is on everywhere → every new public declaration is `public` with KDoc.
- New tests live in `commonTest`, use `kotlin("test")`, and mirror the existing test style
(`TreeNodeV4Test.kt`, `TreeNodeNavigationTest.kt`, …).
- Add a bullet to `CHANGELOG.md` under `## [Unreleased]``### Added` (do **not** bump
`PUBLISH_VERSION`; releases are a separate manual step).
- Regenerate the binary-compatibility baseline with `./gradlew apiDump`; verify with `apiCheck`.
- Do not modify the core public surface in a breaking way — these are additive only.
## #34 — Structural mutation helpers → **members on `TreeNode`**
Members (not extensions) because they need the private `_children`/`_parent` and the cycle/parent
validation.
- Extract the existing inline validation from `addChild` into a private
`validateAttachable(child)` and reuse it.
- `insertChild(index: Int, child)` — validated insert at index (bounds `0.._children.size`).
- `removeChildAt(index: Int): TreeNode<T>` — remove and return the detached child.
- `replaceChild(index: Int, child): TreeNode<T>` — swap, return the old (now detached) child.
- `moveChild(child, toIndex): Boolean` — reorder an existing direct child; no re-parent/cycle
check needed (it is already a child); `false` if `child` is not a direct child.
- `addChildren(vararg children)` — validated append of several (per-child `addChild` semantics).
- `sortChildren(comparator: Comparator<TreeNode<T>>)` — stable in-place reorder.
## #35 — Query algorithms → **extensions** in new `TreeNodeQueryExt.kt`
Built on the public API (`ancestors()`, `parent`, `depth()`, sequences). Return `null` when the
two nodes are unrelated (different trees).
- `lowestCommonAncestor(other): TreeNode<T>?` — deepest common node; includes self/other as
candidates (`LCA(a, a) == a`, `LCA(a, descendantOfA) == a`).
- `distance(other): Int?``depth(this) + depth(other) - 2 * depth(lca)`.
- `pathBetween(other): List<TreeNode<T>>?``[this … lca … other]`.
- `contains(value): Boolean` — value search over the subtree, including the receiver.
Document complexity (parent-walk based; O(depth) for LCA/distance, O(n) for `contains`).
## #36 — Customizable `prettyString()` → **extension** in new `TreeNodePrettyPrintExt.kt`
- `data class TreeConnectors(branch, lastBranch, vertical, empty)` with a `companion`:
`Default` (current Unicode box-drawing) and `Ascii`.
- `fun TreeNode<T>.prettyString(connectors = TreeConnectors.Default,
render: (value: T, depth: Int, isLast: Boolean) -> String = { v, _, _ -> v.toString() }): String`.
- The no-arg member `prettyString()` is unchanged; member resolution wins for `node.prettyString()`,
so existing behaviour and output are byte-for-byte identical.
## #33 — Immutable variant → **new module `:tree-structure-immutable`**
Largest item; fully isolated from the other three except for `settings.gradle.kts`,
`libs.versions.toml`, the root `build.gradle.kts` Dokka aggregation block, and `CHANGELOG.md`.
- `settings.gradle.kts`: `include(":tree-structure-immutable")`.
- New `build.gradle.kts` mirroring the serialization module's KMP target matrix; deps
`api(project(":"))` + `kotlinx-collections-immutable`.
- `libs.versions.toml`: add `kotlinx-collections-immutable` (a recent stable, e.g. 0.3.8) and
wire it.
- Root `build.gradle.kts`: add `dokka(project(":tree-structure-immutable"))` to the aggregation.
- `ImmutableTreeNode<T>` backed by `persistentListOf` children; `addChild` / `removeChild` /
`mapValues` return a new root with unchanged subtrees structurally shared. Mirror pre/post/
level-order traversal helpers.
- Its own `tree-structure-immutable/api/` baseline via `apiDump`.
## Orchestration
- Four git worktrees off `origin/master`, one branch each (`feat/...`), for full isolation — no
collisions on `TreeNode.kt`, `api/*.api`, or `CHANGELOG.md`.
- A workflow pipelines each issue: implement (code + KDoc + tests + CHANGELOG + `apiDump`) and
verify locally (`jvmTest` + `apiCheck`), then an adversarial reviewer checks issue-conformance,
test quality, invariants, explicit API, `.api` freshness, and that it builds. Local checks are
JVM-only for speed; CI validates the full KMP matrix on each PR.
- Then push each passing branch and open a PR (`Closes #NN`); remove the worktrees afterward.

View File

@@ -2,3 +2,9 @@ kotlin.code.style=official
# Dokka Gradle Plugin v2 (https://kotl.in/dokka-gradle-migration)
org.jetbrains.dokka.experimental.gradle.pluginMode=V2Enabled
org.jetbrains.dokka.experimental.gradle.pluginMode.noWarn=true
# Android: Compose pulls AndroidX artifacts, which AGP requires this flag to consume.
android.useAndroidX=true
# AGP loads many classes into the Gradle daemon's Metaspace; combined with the KMP
# matrix, binary-compatibility-validator, Kover and Dokka in a single build, the
# default 512m heap / 384m Metaspace is exhausted (daemon OOM). Raise both.
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8

View File

@@ -1,5 +1,9 @@
[versions]
kotlin = "2.1.0"
agp = "8.7.2"
androidCompileSdk = "35"
androidMinSdk = "21"
activityCompose = "1.9.3"
dokka = "2.2.0"
mavenPublish = "0.34.0"
binaryCompatibilityValidator = "0.16.3"
@@ -11,7 +15,10 @@ composeMultiplatform = "1.7.3"
[plugins]
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
androidLibrary = { id = "com.android.library", version.ref = "agp" }
androidApplication = { id = "com.android.application", version.ref = "agp" }
dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" }
mavenPublish = { id = "com.vanniktech.maven.publish", version.ref = "mavenPublish" }
binaryCompatibilityValidator = { id = "org.jetbrains.kotlinx.binary-compatibility-validator", version.ref = "binaryCompatibilityValidator" }
@@ -24,3 +31,4 @@ kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-c
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" }
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }

View File

@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

View File

@@ -0,0 +1,48 @@
plugins {
alias(libs.plugins.androidApplication)
alias(libs.plugins.kotlinAndroid)
alias(libs.plugins.composeMultiplatform)
alias(libs.plugins.composeCompiler)
}
repositories {
google()
mavenCentral()
}
kotlin {
jvmToolchain(21)
// Match the Kotlin bytecode target to the Java level in android.compileOptions below.
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
android {
namespace = "com.github.adriankuta.treestructure.sample"
compileSdk = libs.versions.androidCompileSdk.get().toInt()
defaultConfig {
applicationId = "com.github.adriankuta.treestructure.sample"
minSdk = libs.versions.androidMinSdk.get().toInt()
targetSdk = libs.versions.androidCompileSdk.get().toInt()
versionCode = 1
versionName = rootProject.version.toString()
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
implementation(project(":"))
implementation(project(":tree-structure-compose"))
implementation(compose.foundation)
implementation(compose.material3)
implementation(compose.components.uiToolingPreview)
implementation(libs.androidx.activity.compose)
debugImplementation(compose.uiTooling)
}

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:label="Tree Sample"
android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,73 @@
package com.github.adriankuta.treestructure.sample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.github.adriankuta.datastructure.tree.TreeNode
import com.github.adriankuta.datastructure.tree.compose.LazyTree
import com.github.adriankuta.datastructure.tree.compose.TreeNodeRow
import com.github.adriankuta.datastructure.tree.tree
import org.jetbrains.compose.ui.tooling.preview.Preview
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
TreeSampleScreen()
}
}
}
}
}
/** Renders the [sampleTree] with the library's default [TreeNodeRow] via the one-line [LazyTree]. */
@Composable
fun TreeSampleScreen() {
LazyTree(sampleTree())
}
private fun sampleTree(): TreeNode<String> = tree("World") {
child("North America") {
child("USA")
child("Canada")
}
child("Europe") {
child("Poland")
child("Germany")
child("Spain")
}
child("Asia") {
child("Japan")
child("India")
}
}
@Preview
@Composable
private fun TreeSampleScreenPreview() {
MaterialTheme {
Surface {
TreeSampleScreen()
}
}
}
@Preview
@Composable
private fun TreeNodeRowPreview() {
MaterialTheme {
TreeNodeRow(
node = TreeNode("Europe").apply { addChild(TreeNode("Poland")) },
depth = 1,
expanded = true,
toggle = {},
)
}
}

35
samples/build.gradle.kts Normal file
View File

@@ -0,0 +1,35 @@
plugins {
// No version: the Kotlin Gradle plugin is already on the build classpath via the root
// project's kotlinMultiplatform plugin, so requesting a version here would clash.
kotlin("jvm")
application
}
kotlin {
jvmToolchain(21)
}
application {
mainClass.set("com.github.adriankuta.samples.SamplesKt")
}
repositories {
mavenCentral()
}
dependencies {
implementation(project(":"))
implementation(project(":tree-structure-serialization"))
implementation(project(":tree-structure-coroutines"))
implementation(project(":tree-structure-immutable"))
// ImmutableTreeNode.children returns a PersistentList, so consumers that touch it need
// kotlinx.collections.immutable on their own classpath (the module declares it as implementation).
implementation(libs.kotlinx.collections.immutable)
testImplementation(kotlin("test"))
}
// kotlin("test") auto-selects the JUnit 5 adapter when the test task uses the JUnit Platform.
tasks.test {
useJUnitPlatform()
}

View File

@@ -0,0 +1,121 @@
package com.github.adriankuta.samples
import com.github.adriankuta.datastructure.tree.TreeNode
import com.github.adriankuta.datastructure.tree.ancestors
import com.github.adriankuta.datastructure.tree.anyNode
import com.github.adriankuta.datastructure.tree.countNodes
import com.github.adriankuta.datastructure.tree.deepCopy
import com.github.adriankuta.datastructure.tree.distance
import com.github.adriankuta.datastructure.tree.filterNodes
import com.github.adriankuta.datastructure.tree.findNode
import com.github.adriankuta.datastructure.tree.isLeaf
import com.github.adriankuta.datastructure.tree.leaves
import com.github.adriankuta.datastructure.tree.levelOrderSequence
import com.github.adriankuta.datastructure.tree.lowestCommonAncestor
import com.github.adriankuta.datastructure.tree.mapValues
import com.github.adriankuta.datastructure.tree.pathBetween
import com.github.adriankuta.datastructure.tree.preOrderSequence
import com.github.adriankuta.datastructure.tree.structurallyEquals
import com.github.adriankuta.datastructure.tree.tree
import com.github.adriankuta.datastructure.tree.coroutines.asFlow
import com.github.adriankuta.datastructure.tree.coroutines.preOrderFlow
import com.github.adriankuta.datastructure.tree.immutable.ImmutableTreeNode
import com.github.adriankuta.datastructure.tree.immutable.preOrder
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
import com.github.adriankuta.datastructure.tree.serialization.TreeNodeDto
import com.github.adriankuta.datastructure.tree.serialization.toDto
import com.github.adriankuta.datastructure.tree.serialization.toTreeNode
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
private fun sampleTree(): TreeNode<String> = tree("World") {
child("North America") {
child("USA")
}
child("Europe") {
child("Poland")
child("Germany")
}
}
/** Core API: DSL, pretty-print, traversal, navigation, functional, query, utilities, mutation. */
fun coreSample(): String = buildString {
val root = sampleTree()
appendLine("prettyString():")
append(root.prettyString())
appendLine()
appendLine("pre-order: " + root.preOrderSequence().map { it.value }.toList())
appendLine("level-order: " + root.levelOrderSequence().map { it.value }.toList())
val usa = root.findNode { it == "USA" }!!
val poland = root.findNode { it == "Poland" }!!
appendLine("usa.depth(): " + usa.depth())
appendLine("usa.ancestors(): " + usa.ancestors().map { it.value })
appendLine("root.leaves(): " + root.leaves().map { it.value })
appendLine("usa.isLeaf: " + usa.isLeaf)
appendLine("anyNode == Poland: " + root.anyNode { it == "Poland" })
appendLine("filterNodes len>5: " + root.filterNodes { it.length > 5 }.map { it.value })
appendLine("countNodes 'U*': " + root.countNodes { it.startsWith("U") })
appendLine("mapValues length: " + root.mapValues { it.length }.preOrderSequence().map { it.value }.toList())
appendLine("deepCopy equals: " + root.structurallyEquals(root.deepCopy()))
appendLine("lowestCommonAncestor(USA, Poland): " + usa.lowestCommonAncestor(poland)?.value)
appendLine("pathBetween(USA, Poland): " + usa.pathBetween(poland)?.map { it.value })
appendLine("distance(USA, Poland): " + usa.distance(poland))
appendLine("nodeCount(): " + root.nodeCount())
appendLine("height(): " + root.height())
appendLine("path(USA): " + root.path(usa)?.map { it.value })
// Mutation on a copy; the shared sampleTree() stays untouched.
val mutable = root.deepCopy()
mutable.addChild(TreeNode("Asia"))
mutable.findNode { it == "Germany" }?.detach()
appendLine("after addChild(Asia) + detach(Germany): " + mutable.preOrderSequence().map { it.value }.toList())
}
/** Serialization satellite: TreeNode -> TreeNodeDto -> JSON -> TreeNodeDto -> TreeNode round-trip. */
fun serializationSample(): String = buildString {
val root = sampleTree()
val json = Json.encodeToString(root.toDto())
appendLine("JSON: $json")
val restored = Json.decodeFromString<TreeNodeDto<String>>(json).toTreeNode()
appendLine("round-trips structurallyEquals: " + root.structurallyEquals(restored))
}
/** Coroutines satellite: traverse the tree as a cold Flow. */
fun coroutinesSample(): String = buildString {
val root = sampleTree()
val preOrder = runBlocking { root.preOrderFlow().map { it.value }.toList() }
val levelOrder = runBlocking { root.asFlow(TreeNodeIterators.LevelOrder).map { it.value }.toList() }
appendLine("preOrderFlow(): $preOrder")
appendLine("asFlow(LevelOrder): $levelOrder")
}
/** Immutable satellite: persistent tree; every op returns a new root, leaving the original intact. */
fun immutableSample(): String = buildString {
val root = ImmutableTreeNode("World").addChild(ImmutableTreeNode("Europe"))
val bigger = root.addChild(ImmutableTreeNode("Asia"))
appendLine("root.children: " + root.children.map { it.value })
appendLine("bigger.children: " + bigger.children.map { it.value })
appendLine("root unchanged: " + (root.children.size == 1))
appendLine("bigger.mapValues uppercase preOrder: " + bigger.mapValues { it.uppercase() }.preOrder().map { it.value })
}
fun main() {
println("== Core ==")
println(coreSample())
println("== Serialization ==")
println(serializationSample())
println("== Coroutines ==")
println(coroutinesSample())
println("== Immutable ==")
println(immutableSample())
}

View File

@@ -0,0 +1,46 @@
package com.github.adriankuta.samples
import kotlin.test.Test
import kotlin.test.assertContains
class SamplesTest {
@Test
fun coreSampleRendersTreeAndTraversals() {
val out = coreSample()
assertContains(
out,
"World\n" +
"├── North America\n" +
"│ └── USA\n" +
"└── Europe\n" +
" ├── Poland\n" +
" └── Germany\n",
)
assertContains(out, "[World, North America, USA, Europe, Poland, Germany]")
assertContains(out, "[North America, World]") // usa.ancestors()
assertContains(out, "[USA, Poland, Germany]") // root.leaves()
}
@Test
fun serializationSampleRoundTrips() {
val out = serializationSample()
assertContains(out, "\"World\"")
assertContains(out, "round-trips structurallyEquals: true")
}
@Test
fun coroutinesSampleCollectsFlows() {
val out = coroutinesSample()
assertContains(out, "preOrderFlow(): [World, North America, USA, Europe, Poland, Germany]")
assertContains(out, "asFlow(LevelOrder): [World, North America, Europe, USA, Poland, Germany]")
}
@Test
fun immutableSampleLeavesRootUnchanged() {
val out = immutableSample()
assertContains(out, "root.children: [Europe]")
assertContains(out, "bigger.children: [Europe, Asia]")
assertContains(out, "root unchanged: true")
}
}

View File

@@ -1,6 +1,16 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = "tree-structure"
include(":tree-structure-serialization")
include(":tree-structure-coroutines")
include(":tree-structure-compose")
include(":tree-structure-immutable")
include(":samples")
include(":samples-android")

View File

@@ -0,0 +1,455 @@
package com.github.adriankuta.datastructure.tree
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Property-based tests for traversal and structural invariants (issue #38).
*
* Instead of a handful of hand-written example trees, each property is checked against many
* randomly generated trees. Generation is seeded ([BASE_SEED] + iteration index), so a failing case
* is fully reproducible: rerun [randomTree] with the seed printed in the failure message. No
* external dependency is used, so these run on every Kotlin target (JVM/JS/Wasm/Native).
*/
class TreeNodePropertyTest {
// -----------------------------------------------------------------------------------------
// Traversal node-set invariants
// -----------------------------------------------------------------------------------------
@Test
fun allThreeOrdersVisitTheSameSetOfNodes() = forEachRandomTree { tree, seed ->
val pre = tree.preOrderSequence().toList()
val post = tree.postOrderSequence().toList()
val level = tree.levelOrderSequence().toList()
assertEquals(pre.toSet(), post.toSet(), "pre vs post node set (seed=$seed)")
assertEquals(pre.toSet(), level.toSet(), "pre vs level node set (seed=$seed)")
}
@Test
fun allThreeOrdersHaveTheSameCardinalityAndNoDuplicates() = forEachRandomTree { tree, seed ->
val pre = tree.preOrderSequence().toList()
val post = tree.postOrderSequence().toList()
val level = tree.levelOrderSequence().toList()
val expectedSize = tree.nodeCount() + 1 // traversal includes the root; nodeCount excludes it
assertEquals(expectedSize, pre.size, "pre-order size (seed=$seed)")
assertEquals(expectedSize, post.size, "post-order size (seed=$seed)")
assertEquals(expectedSize, level.size, "level-order size (seed=$seed)")
assertEquals(pre.size, pre.toSet().size, "pre-order visits no node twice (seed=$seed)")
assertEquals(post.size, post.toSet().size, "post-order visits no node twice (seed=$seed)")
assertEquals(level.size, level.toSet().size, "level-order visits no node twice (seed=$seed)")
}
// -----------------------------------------------------------------------------------------
// Per-order ordering invariants
// -----------------------------------------------------------------------------------------
@Test
fun preOrderEmitsEverySubtreeAsAContiguousBlockAfterItsRoot() = forEachRandomTree { tree, seed ->
val pre = tree.preOrderSequence().toList()
val index = pre.indexMap()
for (node in pre) {
val start = index.getValue(node) + 1
val block = pre.subList(start, start + node.nodeCount())
assertEquals(node.descendants().toSet(), block.toSet(), "pre-order subtree of $node (seed=$seed)")
}
}
@Test
fun postOrderEmitsEverySubtreeAsAContiguousBlockBeforeItsRoot() = forEachRandomTree { tree, seed ->
val post = tree.postOrderSequence().toList()
val index = post.indexMap()
for (node in post) {
val end = index.getValue(node)
val block = post.subList(end - node.nodeCount(), end)
assertEquals(node.descendants().toSet(), block.toSet(), "post-order subtree of $node (seed=$seed)")
}
}
@Test
fun levelOrderVisitsNodesInNonDecreasingDepth() = forEachRandomTree { tree, seed ->
val depths = tree.levelOrderSequence().map { it.depth() }.toList()
for (i in 1 until depths.size) {
assertTrue(depths[i - 1] <= depths[i], "level-order depth not monotonic at $i (seed=$seed)")
}
}
@Test
fun preAndLevelOrderVisitEveryParentBeforeItsChildren() = forEachRandomTree { tree, seed ->
for (order in listOf(tree.preOrderSequence(), tree.levelOrderSequence())) {
val index = order.toList().indexMap()
for (node in index.keys) {
for (child in node.children) {
assertTrue(index.getValue(node) < index.getValue(child), "parent before child (seed=$seed)")
}
}
}
}
@Test
fun postOrderVisitsEveryChildBeforeItsParent() = forEachRandomTree { tree, seed ->
val index = tree.postOrderSequence().toList().indexMap()
for (node in index.keys) {
for (child in node.children) {
assertTrue(index.getValue(child) < index.getValue(node), "child before parent (seed=$seed)")
}
}
}
// -----------------------------------------------------------------------------------------
// depth / height invariants
// -----------------------------------------------------------------------------------------
@Test
fun depthMatchesAnIndependentBfsLevelAndEveryChildIsOneDeeper() = forEachRandomTree { tree, seed ->
assertEquals(0, tree.depth(), "root depth (seed=$seed)")
// Independent oracle: derive each node's level by walking DOWN through children (BFS), then
// cross-check against depth(), which walks UP through parent pointers. A bug in the parent
// walk cannot corrupt both derivations identically.
val levelByNode = HashMap<TreeNode<Int>, Int>()
levelByNode[tree] = 0
val queue = ArrayDeque<TreeNode<Int>>()
queue.add(tree)
while (queue.isNotEmpty()) {
val node = queue.removeFirst()
for (child in node.children) {
levelByNode[child] = levelByNode.getValue(node) + 1
queue.add(child)
}
}
for (node in tree) {
assertEquals(levelByNode.getValue(node), node.depth(), "depth matches BFS level (seed=$seed)")
for (child in node.children) {
assertEquals(node.depth() + 1, child.depth(), "child depth (seed=$seed)")
}
}
}
@Test
fun heightEqualsDeepestDescendantDistanceAndLeavesHaveHeightZero() = forEachRandomTree { tree, seed ->
for (node in tree) {
val expected = node.asSequence().maxOf { it.depth() } - node.depth()
assertEquals(expected, node.height(), "height of $node (seed=$seed)")
if (node.isLeaf) assertEquals(0, node.height(), "leaf height (seed=$seed)")
}
}
// -----------------------------------------------------------------------------------------
// nodeCount invariants
// -----------------------------------------------------------------------------------------
@Test
fun nodeCountEqualsDescendantCountForEveryNode() = forEachRandomTree { tree, seed ->
for (node in tree) {
// Independent oracle: nodeCount() walks an explicit stack; the pre-order sequence is a
// separate traversal, so agreeing pins the count without circularity.
assertEquals(node.asSequence().count() - 1, node.nodeCount(), "nodeCount vs traversal (seed=$seed)")
// Recursive self-consistency: a node's count is the sum of (each child + its subtree).
assertEquals(node.children.sumOf { it.nodeCount() + 1 }, node.nodeCount(), "nodeCount recursive sum (seed=$seed)")
}
}
@Test
fun nodeCountAndTraversalStayConsistentAcrossAttachAndDetach() = forEachRandomTree { tree, seed ->
// A second, independent tree we graft onto a random node of `tree`, then remove again.
val grafted = randomTree(Random(seed * 31 + 7), maxNodes = 20)
val host = tree.toList().random(Random(seed xor SELECT_SALT))
val countBefore = tree.nodeCount()
val graftSize = grafted.nodeCount() + 1 // the grafted root plus its descendants
host.addChild(grafted)
assertEquals(countBefore + graftSize, tree.nodeCount(), "nodeCount after addChild (seed=$seed)")
assertTrue(tree.toSet().containsAll(grafted.toList()), "grafted nodes now reachable (seed=$seed)")
assertSameNode(host, grafted.parent, "graft re-parented (seed=$seed)")
assertTrue(grafted.detach(), "detach returns true (seed=$seed)")
assertEquals(countBefore, tree.nodeCount(), "nodeCount restored after detach (seed=$seed)")
assertTrue(grafted.isRoot, "grafted is a root again (seed=$seed)")
assertFalse(tree.toSet().contains(grafted), "grafted no longer reachable (seed=$seed)")
}
@Test
fun removeAndReinsertKeepNodeCountAndPointersConsistent() = forEachRandomTree { tree, seed ->
val rnd = Random(seed xor 0x55AA_55AAL)
val parents = tree.toList().filter { it.children.isNotEmpty() }
if (parents.isEmpty()) return@forEachRandomTree // single-node tree: nothing to remove
val parent = parents.random(rnd)
val countBefore = tree.nodeCount()
val index = rnd.nextInt(parent.children.size)
val subtreeSize = parent.children[index].nodeCount() + 1
val removed = parent.removeChildAt(index)
assertTrue(removed.isRoot, "removeChildAt detaches the child (seed=$seed)")
assertEquals(countBefore - subtreeSize, tree.nodeCount(), "nodeCount drops by the subtree (seed=$seed)")
assertFalse(tree.toSet().contains(removed), "removed subtree no longer reachable (seed=$seed)")
val insertAt = rnd.nextInt(parent.children.size + 1)
parent.insertChild(insertAt, removed)
assertEquals(countBefore, tree.nodeCount(), "nodeCount restored after insertChild (seed=$seed)")
assertSameNode(parent, removed.parent, "re-inserted subtree is re-parented (seed=$seed)")
assertSameNode(removed, parent.children[insertAt], "re-inserted at the requested index (seed=$seed)")
for (node in tree) {
for (child in node.children) {
assertSameNode(node, child.parent, "parent pointers stay consistent (seed=$seed)")
}
}
}
@Test
fun clearRemovesEveryDescendantAndKeepsTheNodeAttached() = forEachRandomTree { tree, seed ->
val node = tree.toList().random(Random(seed xor SELECT_SALT))
val parentBefore = node.parent
node.clear()
assertEquals(0, node.nodeCount(), "nodeCount after clear (seed=$seed)")
assertTrue(node.children.isEmpty(), "children empty after clear (seed=$seed)")
assertSameNode(parentBefore, node.parent, "node keeps its own parent after clear (seed=$seed)")
}
// -----------------------------------------------------------------------------------------
// Structural / parent-pointer invariants
// -----------------------------------------------------------------------------------------
@Test
fun parentAndChildPointersAreConsistentForEveryNode() = forEachRandomTree { tree, seed ->
assertTrue(tree.isRoot, "generated root is a root (seed=$seed)")
for (node in tree) {
assertEquals(node.parent == null, node.isRoot, "isRoot matches null parent (seed=$seed)")
assertSameNode(tree, node.root(), "root() returns the tree root (seed=$seed)")
for (child in node.children) {
assertSameNode(node, child.parent, "child points back to parent (seed=$seed)")
}
val parent = node.parent
if (parent != null) {
assertTrue(parent.children.any { it === node }, "node listed in its parent (seed=$seed)")
// Note: TreeNode is Iterable, so `list + node` would flatten the node's subtree —
// compare siblings against the parent's other children directly instead.
assertEquals(
parent.children.filter { it !== node }.toSet(),
node.siblings().toSet(),
"siblings are exactly the parent's other children (seed=$seed)",
)
assertFalse(node.siblings().any { it === node }, "siblings exclude self (seed=$seed)")
}
}
}
@Test
fun ancestorChainOfEveryNodeTerminatesAtTheRoot() = forEachRandomTree { tree, seed ->
for (node in tree) {
val ancestors = node.ancestors()
assertEquals(node.depth(), ancestors.size, "ancestor count equals depth (seed=$seed)")
if (ancestors.isNotEmpty()) {
assertSameNode(tree, ancestors.last(), "topmost ancestor is the root (seed=$seed)")
}
ancestors.forEach { assertTrue(it.depth() < node.depth(), "ancestors are shallower (seed=$seed)") }
}
}
@Test
fun leavesAreExactlyTheChildlessNodes() = forEachRandomTree { tree, seed ->
assertEquals(tree.asSequence().filter { it.isLeaf }.toSet(), tree.leaves().toSet(), "leaves (seed=$seed)")
assertTrue(tree.leaves().all { it.isLeaf }, "every leaf is childless (seed=$seed)")
assertEquals(tree.toList().size, tree.descendants().size + 1, "descendants + self (seed=$seed)")
}
// -----------------------------------------------------------------------------------------
// Transform / structural-equality invariants
// -----------------------------------------------------------------------------------------
@Test
fun deepCopyAndIdentityMapPreserveShapeWithFreshNodes() = forEachRandomTree { tree, seed ->
assertTrue(tree.structurallyEquals(tree), "structurallyEquals is reflexive (seed=$seed)")
val copy = tree.deepCopy()
assertTrue(copy.structurallyEquals(tree), "deepCopy is structurally equal (seed=$seed)")
assertEquals(tree.nodeCount(), copy.nodeCount(), "deepCopy node count (seed=$seed)")
assertEquals(tree.height(), copy.height(), "deepCopy height (seed=$seed)")
assertTrue(copy.toSet().intersect(tree.toSet()).isEmpty(), "deepCopy shares no node object (seed=$seed)")
val mapped = tree.mapValues { it }
assertTrue(mapped.structurallyEquals(tree), "identity mapValues preserves structure (seed=$seed)")
assertTrue(mapped.toSet().intersect(tree.toSet()).isEmpty(), "mapValues yields fresh nodes (seed=$seed)")
}
// -----------------------------------------------------------------------------------------
// Functional / value-query invariants
// -----------------------------------------------------------------------------------------
@Test
fun valueQueriesAgreeWithTraversalOverUniqueValues() = forEachRandomTree { tree, seed ->
val values = tree.asSequence().map { it.value }.toList()
assertEquals(values.size, values.toSet().size, "generated values are unique (seed=$seed)")
assertEquals(values.size, tree.countNodes { true }, "countNodes(true) == size (seed=$seed)")
for (value in values) {
assertTrue(tree.contains(value), "contains present value $value (seed=$seed)")
assertNotNull(tree.findNode { it == value }, "findNode present value $value (seed=$seed)")
}
val absent = values.max() + 1 // values are unique and dense from 0, so this one is absent
assertFalse(tree.contains(absent), "absent value not contained (seed=$seed)")
}
// -----------------------------------------------------------------------------------------
// Query algorithms (lca / distance / pathBetween)
// -----------------------------------------------------------------------------------------
@Test
fun lowestCommonAncestorIsTheDeepestSharedAncestor() = forEachRandomTree { tree, seed ->
val nodes = tree.toList()
val rnd = Random(seed xor 0x1234_5678L)
repeat(PAIRS_PER_TREE) {
val a = nodes.random(rnd)
val b = nodes.random(rnd)
val lca = a.lowestCommonAncestor(b)
assertNotNull(lca, "lca within one tree is non-null (seed=$seed)")
assertSameNode(lca, b.lowestCommonAncestor(a), "lca is symmetric (seed=$seed)")
val ancestorsAndSelfA = (listOf(a) + a.ancestors()).toSet()
val ancestorsAndSelfB = (listOf(b) + b.ancestors()).toSet()
assertTrue(lca in ancestorsAndSelfA, "lca is an ancestor-or-self of a (seed=$seed)")
assertTrue(lca in ancestorsAndSelfB, "lca is an ancestor-or-self of b (seed=$seed)")
// Common ancestors form a chain, so the deepest one is unique; it must be the lca itself.
val deepestShared = ancestorsAndSelfA.intersect(ancestorsAndSelfB).maxByOrNull { it.depth() }
assertSameNode(deepestShared, lca, "lca is the deepest shared ancestor (seed=$seed)")
}
}
@Test
fun distanceAndPathBetweenAreConsistent() = forEachRandomTree { tree, seed ->
val nodes = tree.toList()
val rnd = Random(seed xor 0x0F0F_0F0FL)
repeat(PAIRS_PER_TREE) {
val a = nodes.random(rnd)
val b = nodes.random(rnd)
val distance = a.distance(b)
assertNotNull(distance, "distance within one tree is non-null (seed=$seed)")
assertTrue(distance >= 0, "distance is non-negative (seed=$seed)")
assertEquals(distance, b.distance(a), "distance is symmetric (seed=$seed)")
val path = a.pathBetween(b)
assertNotNull(path, "path within one tree is non-null (seed=$seed)")
assertSameNode(a, path.first(), "path starts at a (seed=$seed)")
assertSameNode(b, path.last(), "path ends at b (seed=$seed)")
assertEquals(distance, path.size - 1, "distance == path edges (seed=$seed)")
assertEquals(path.size, path.toSet().size, "path has no repeated node (seed=$seed)")
for (i in 1 until path.size) {
val (p, q) = path[i - 1] to path[i]
assertTrue(p.parent === q || q.parent === p, "consecutive path nodes are an edge (seed=$seed)")
}
}
}
@Test
fun distanceAndPathToSelfAreTrivial() = forEachRandomTree { tree, seed ->
val node = tree.toList().random(Random(seed xor SELECT_SALT))
assertEquals(0, node.distance(node), "distance to self is 0 (seed=$seed)")
assertSameNode(node, node.lowestCommonAncestor(node), "lca with self is self (seed=$seed)")
assertEquals(listOf(node), node.pathBetween(node), "path to self is the singleton (seed=$seed)")
}
// -----------------------------------------------------------------------------------------
// Termination and ordering on degenerate (deep / wide) trees
// -----------------------------------------------------------------------------------------
@Test
fun everyTraversalTerminatesAndIsCorrectlyOrderedOnADeepChain() {
val depth = 5_000
val root = TreeNode(0)
var current = root
for (i in 1..depth) {
val child = TreeNode(i)
current.addChild(child)
current = child
}
// On a chain pre- and level-order descend the chain; post-order returns it leaf-first. These
// pin the actual ordering, not merely that every order visits the same number of nodes.
assertContentEquals((0..depth).toList(), root.preOrderSequence().map { it.value }.toList(), "pre-order of a chain")
assertContentEquals((0..depth).toList(), root.levelOrderSequence().map { it.value }.toList(), "level-order of a chain")
assertContentEquals((depth downTo 0).toList(), root.postOrderSequence().map { it.value }.toList(), "post-order of a chain")
assertEquals(depth, root.height(), "height on deep chain")
assertEquals(depth, root.nodeCount(), "nodeCount on deep chain")
assertEquals(depth, current.depth(), "depth of the deepest node")
}
@Test
fun everyTraversalTerminatesAndIsCorrectlyOrderedOnAWideTree() {
val width = 5_000
val root = TreeNode(0)
for (i in 1..width) root.addChild(TreeNode(i))
// pre- and level-order list the root then its children in order; post-order lists the
// children in order then the root.
assertContentEquals(listOf(0) + (1..width), root.preOrderSequence().map { it.value }.toList(), "pre-order of a star")
assertContentEquals(listOf(0) + (1..width), root.levelOrderSequence().map { it.value }.toList(), "level-order of a star")
assertContentEquals((1..width).toList() + 0, root.postOrderSequence().map { it.value }.toList(), "post-order of a star")
assertEquals(1, root.height(), "height on wide tree")
assertEquals(width, root.nodeCount(), "nodeCount on wide tree")
assertTrue(root.children.all { it.depth() == 1 }, "every child of a wide root is at depth 1")
}
}
// ---------------------------------------------------------------------------------------------
// Random tree generation + property harness
// ---------------------------------------------------------------------------------------------
private const val ITERATIONS = 200
private const val BASE_SEED = 0x5EEDL
/** How many random node pairs each query property samples per generated tree. */
private const val PAIRS_PER_TREE = 8
/** Decorrelates node-selection RNGs from the tree-construction RNG that shares the same seed. */
private const val SELECT_SALT = 0x2545_F491_4F6C_DD1DL
/** Runs [property] against [iterations] freshly generated random trees, one per derived seed. */
private fun forEachRandomTree(
iterations: Int = ITERATIONS,
maxNodes: Int = 80,
property: (tree: TreeNode<Int>, seed: Long) -> Unit,
) {
for (i in 0 until iterations) {
val seed = BASE_SEED + i
property(randomTree(Random(seed), maxNodes), seed)
}
}
/**
* Builds a random tree of `1..[maxNodes]` nodes by uniform random attachment: each new node (value
* `1, 2, …`) is attached under a uniformly chosen existing node. This samples a broad spread of
* shapes — chains, bushy, and lopsided trees, plus single-node trees — without the left-heavy skew
* of a depth-first node budget, and is iterative so it never risks the call stack. Values are unique
* and dense from `0` (the root). Deterministic for a given [random], so the seed reproduces it.
*/
private fun randomTree(random: Random, maxNodes: Int): TreeNode<Int> {
val size = random.nextInt(1, maxNodes + 1)
val root = TreeNode(0)
val nodes = ArrayList<TreeNode<Int>>(size)
nodes.add(root)
for (value in 1 until size) {
val parent = nodes[random.nextInt(nodes.size)]
val child = TreeNode(value)
parent.addChild(child)
nodes.add(child)
}
return root
}
/** Maps each node to its position in this traversal. Keys compare by identity (TreeNode equality). */
private fun List<TreeNode<Int>>.indexMap(): Map<TreeNode<Int>, Int> =
withIndex().associate { (i, node) -> node to i }
/** Asserts two references point at the same node object (TreeNode uses identity equality). */
private fun assertSameNode(expected: TreeNode<*>?, actual: TreeNode<*>?, message: String) {
assertTrue(expected === actual, "$message — expected same node as $expected but was $actual")
}

View File

@@ -0,0 +1,9 @@
public final class com/github/adriankuta/datastructure/tree/compose/LazyTreeKt {
public static final fun LazyTree (Lcom/github/adriankuta/datastructure/tree/TreeNode;Landroidx/compose/ui/Modifier;ZLkotlin/jvm/functions/Function6;Landroidx/compose/runtime/Composer;II)V
public static final fun LazyTree-hGBTI10 (Lcom/github/adriankuta/datastructure/tree/TreeNode;Landroidx/compose/ui/Modifier;ZFLkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V
}
public final class com/github/adriankuta/datastructure/tree/compose/TreeNodeRowKt {
public static final fun TreeNodeRow-PfoAEA0 (Lcom/github/adriankuta/datastructure/tree/TreeNode;IZLkotlin/jvm/functions/Function0;Landroidx/compose/ui/Modifier;FLkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V
}

View File

@@ -0,0 +1,9 @@
public final class com/github/adriankuta/datastructure/tree/compose/LazyTreeKt {
public static final fun LazyTree (Lcom/github/adriankuta/datastructure/tree/TreeNode;Landroidx/compose/ui/Modifier;ZLkotlin/jvm/functions/Function6;Landroidx/compose/runtime/Composer;II)V
public static final fun LazyTree-hGBTI10 (Lcom/github/adriankuta/datastructure/tree/TreeNode;Landroidx/compose/ui/Modifier;ZFLkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V
}
public final class com/github/adriankuta/datastructure/tree/compose/TreeNodeRowKt {
public static final fun TreeNodeRow-PfoAEA0 (Lcom/github/adriankuta/datastructure/tree/TreeNode;IZLkotlin/jvm/functions/Function0;Landroidx/compose/ui/Modifier;FLkotlin/jvm/functions/Function1;Landroidx/compose/runtime/Composer;II)V
}

View File

@@ -1,4 +0,0 @@
public final class com/github/adriankuta/datastructure/tree/compose/LazyTreeKt {
public static final fun LazyTree (Lcom/github/adriankuta/datastructure/tree/TreeNode;Landroidx/compose/ui/Modifier;ZLkotlin/jvm/functions/Function6;Landroidx/compose/runtime/Composer;II)V
}

View File

@@ -2,6 +2,7 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidLibrary)
alias(libs.plugins.composeMultiplatform)
alias(libs.plugins.composeCompiler)
alias(libs.plugins.dokka)
@@ -68,6 +69,14 @@ kotlin {
jvm()
androidTarget {
publishLibraryVariants("release")
// Match the Android variant's Kotlin bytecode to the Java level set in compileOptions.
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@OptIn(ExperimentalWasmDsl::class)
wasmJs {
browser()
@@ -85,3 +94,15 @@ kotlin {
}
}
}
android {
namespace = "com.github.adriankuta.datastructure.tree.compose"
compileSdk = libs.versions.androidCompileSdk.get().toInt()
defaultConfig {
minSdk = libs.versions.androidMinSdk.get().toInt()
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}

View File

@@ -5,6 +5,8 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.github.adriankuta.datastructure.tree.TreeNode
/**
@@ -49,6 +51,35 @@ public fun <T> LazyTree(
}
}
/**
* Convenience overload of [LazyTree] that renders each node with the built-in [TreeNodeRow], so the
* common case is a single call:
*
* ```
* LazyTree(root)
* ```
*
* Use the overload that takes a `nodeContent` lambda when you need full control over a node's look.
*
* @param root the root of the tree to display.
* @param modifier the [Modifier] applied to the underlying [LazyColumn].
* @param initiallyExpanded whether nodes start expanded.
* @param indent the horizontal indentation applied per depth level.
* @param label maps a node's value to the text shown. Defaults to `toString()`.
*/
@Composable
public fun <T> LazyTree(
root: TreeNode<T>,
modifier: Modifier = Modifier,
initiallyExpanded: Boolean = true,
indent: Dp = 16.dp,
label: (T) -> String = { it.toString() },
) {
LazyTree(root, modifier, initiallyExpanded) { node, depth, expanded, toggle ->
TreeNodeRow(node, depth, expanded, toggle, indent = indent, label = label)
}
}
/**
* Flattens the tree into the list of currently-visible `(node, depth)` pairs in pre-order, skipping
* the subtrees of collapsed nodes. Iterative, so it is safe on deep trees.

View File

@@ -0,0 +1,59 @@
package com.github.adriankuta.datastructure.tree.compose
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.github.adriankuta.datastructure.tree.TreeNode
/**
* A sensible default row for a single node in a [LazyTree]. The whole row is clickable to expand or
* collapse, indentation reflects [depth], and a `▾`/`▸` marker precedes non-leaf nodes.
*
* It is intentionally foundation-only (no Material), so using it does not pull a theming dependency
* into your app. For full control over a node's appearance, use the `LazyTree` overload that takes a
* `nodeContent` lambda instead.
*
* ```
* LazyTree(root) { node, depth, expanded, toggle ->
* TreeNodeRow(node, depth, expanded, toggle)
* }
* ```
*
* @param node the node to render.
* @param depth the node's depth in the tree (root = 0), used for indentation.
* @param expanded whether the node is currently expanded.
* @param toggle flips this node's expansion state; invoked when the row is clicked.
* @param modifier the [Modifier] applied to the row.
* @param indent the horizontal indentation applied per depth level.
* @param label maps the node's value to the text shown. Defaults to `toString()`.
*/
@Composable
public fun <T> TreeNodeRow(
node: TreeNode<T>,
depth: Int,
expanded: Boolean,
toggle: () -> Unit,
modifier: Modifier = Modifier,
indent: Dp = 16.dp,
label: (T) -> String = { it.toString() },
) {
val marker = when {
node.children.isEmpty() -> ""
expanded -> ""
else -> ""
}
Row(
modifier = modifier
.fillMaxWidth()
.clickable(onClick = toggle)
.padding(start = indent * depth, top = 8.dp, bottom = 8.dp, end = 8.dp),
) {
BasicText(text = marker + label(node.value))
}
}