Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bec1fe02a7 | ||
|
|
69d19f89e3 | ||
|
|
c9bbea59b0 | ||
|
|
e1f01c4e2d | ||
|
|
c45c5b7afa | ||
|
|
6de95f7976 | ||
|
|
ea0b4fa95c | ||
|
|
9d52b152bd | ||
|
|
0fc7b16664 | ||
|
|
d3086a5ced | ||
|
|
2071084964 | ||
|
|
f51964831a | ||
|
|
60c50f078d | ||
|
|
54f5074483 | ||
|
|
772eeb0465 | ||
|
|
456f889b9c | ||
|
|
c3a4ca5925 | ||
|
|
06dc507590 | ||
|
|
5eaf027dba | ||
|
|
04c3728fcd | ||
|
|
d34050e9af | ||
|
|
2c8381deac | ||
|
|
4aacbc9dbc | ||
|
|
8a4e677ebf | ||
|
|
84e85f3240 | ||
|
|
e34a85ac39 | ||
|
|
c306088ea3 | ||
|
|
308c37720d | ||
|
|
90af315222 | ||
|
|
bd5e4f07ae | ||
|
|
ae4757fb9d | ||
|
|
5dd586f9af | ||
|
|
b69e838a8a | ||
|
|
8a2710339a | ||
|
|
dd773e3b16 | ||
|
|
72c94f280d | ||
|
|
809914274a | ||
|
|
6f16f1cb85 | ||
|
|
cad5b2dd95 | ||
|
|
74a6a65434 | ||
|
|
b0a6c701ae | ||
|
|
1bd47fcb21 | ||
|
|
20bd96918c | ||
|
|
60805b7187 | ||
|
|
12b1df764c | ||
|
|
43b8982b88 |
@@ -1,86 +0,0 @@
|
|||||||
version: 2.1
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
working_directory: ~/code
|
|
||||||
docker:
|
|
||||||
- image: circleci/android:api-29
|
|
||||||
environment:
|
|
||||||
JVM_OPTS: -Xmx3200m
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
|
|
||||||
- run:
|
|
||||||
name: Download Dependencies
|
|
||||||
command: ./gradlew androidDependencies
|
|
||||||
- save_cache:
|
|
||||||
paths:
|
|
||||||
- ~/.gradle
|
|
||||||
key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
|
|
||||||
|
|
||||||
tests:
|
|
||||||
working_directory: ~/code
|
|
||||||
docker:
|
|
||||||
- image: circleci/android:api-29
|
|
||||||
environment:
|
|
||||||
JVM_OPTS: -Xmx3200m
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
|
|
||||||
- store_artifacts:
|
|
||||||
path: app/build/reports
|
|
||||||
destination: reports
|
|
||||||
- run:
|
|
||||||
name: Run Lint Test
|
|
||||||
command: ./gradlew lint
|
|
||||||
- run:
|
|
||||||
name: Run Tests
|
|
||||||
command: ./gradlew lint test
|
|
||||||
- store_artifacts:
|
|
||||||
path: app/build/reports
|
|
||||||
destination: reports
|
|
||||||
- store_test_results:
|
|
||||||
path: app/build/test-results
|
|
||||||
|
|
||||||
deploy:
|
|
||||||
working_directory: ~/code
|
|
||||||
docker:
|
|
||||||
- image: circleci/android:api-29
|
|
||||||
environment:
|
|
||||||
JVM_OPTS: -Xmx3200m
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- restore_cache:
|
|
||||||
key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
|
|
||||||
- run:
|
|
||||||
name: Build Library
|
|
||||||
command: ./gradlew :treedatastructure:assembleRelease
|
|
||||||
- run:
|
|
||||||
name: Export key
|
|
||||||
command: |
|
|
||||||
mkdir treedatastructure/maven
|
|
||||||
echo ${GPG_KEY_CONTENTS} | base64 -d --ignore-garbage > treedatastructure/maven/secret.gpg
|
|
||||||
- run:
|
|
||||||
name: Staging
|
|
||||||
command: ./gradlew :treedatastructure:publishReleasePublicationToSonatypeRepository
|
|
||||||
- run:
|
|
||||||
name: Release Library
|
|
||||||
command: ./gradlew closeAndReleaseRepository
|
|
||||||
|
|
||||||
workflows:
|
|
||||||
version: 2.1
|
|
||||||
build-and-deploy:
|
|
||||||
jobs:
|
|
||||||
- build:
|
|
||||||
filters: # required since `deploy` has tag filters AND requires `build`
|
|
||||||
tags:
|
|
||||||
only: /.*/
|
|
||||||
- deploy:
|
|
||||||
requires:
|
|
||||||
- build
|
|
||||||
filters:
|
|
||||||
tags:
|
|
||||||
only: /v[0-9]{1,3}\.[0-9]{1,3}\.?[0-9]{0,3}/
|
|
||||||
branches:
|
|
||||||
ignore: /.*/
|
|
||||||
38
.github/workflows/publish.yml
vendored
@@ -1,38 +0,0 @@
|
|||||||
name: Publish
|
|
||||||
|
|
||||||
on:
|
|
||||||
release:
|
|
||||||
# We'll run this workflow when a new GitHub release is created
|
|
||||||
types: [released]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
publish:
|
|
||||||
name: Release build and publish
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out code
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
- name: Set up JDK 11
|
|
||||||
uses: actions/setup-java@v2
|
|
||||||
with:
|
|
||||||
distribution: adopt
|
|
||||||
java-version: 11
|
|
||||||
|
|
||||||
# Builds the release artifacts of the library
|
|
||||||
- name: Release build
|
|
||||||
run: ./gradlew :treedatastructure:assembleRelease
|
|
||||||
|
|
||||||
# Generates other artifacts (javadocJar is optional)
|
|
||||||
- name: Source jar and dokka
|
|
||||||
run: ./gradlew androidSourcesJar javadocJar
|
|
||||||
|
|
||||||
# Runs upload, and then closes & releases the repository
|
|
||||||
- name: Publish to MavenCentral
|
|
||||||
run: ./gradlew publishReleasePublicationToSonatypeRepository --max-workers 1 closeAndReleaseSonatypeStagingRepository
|
|
||||||
env:
|
|
||||||
OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }}
|
|
||||||
OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }}
|
|
||||||
SIGNING_KEY_ID: ${{ secrets.SIGNING_KEY_ID }}
|
|
||||||
SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
|
|
||||||
SIGNING_KEY: ${{ secrets.SIGNING_KEY }}
|
|
||||||
SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }}
|
|
||||||
36
.github/workflows/publishRelease.yml
vendored
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
name: Publish
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
# We'll run this workflow when a new GitHub release is created
|
||||||
|
types: [released]
|
||||||
|
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
uses: ./.github/workflows/test.yml
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
|
publish:
|
||||||
|
needs: test
|
||||||
|
name: Publish Production
|
||||||
|
environment: production
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up JDK 21
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '21'
|
||||||
|
|
||||||
|
# Runs upload, and then closes & releases the repository
|
||||||
|
- name: Publish to MavenCentral
|
||||||
|
run: ./gradlew publishToMavenCentral
|
||||||
|
env:
|
||||||
|
ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
|
||||||
|
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }}
|
||||||
|
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_KEY }}
|
||||||
|
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }}
|
||||||
|
SNAPSHOT: false
|
||||||
31
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
name: Test
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches-ignore: [master]
|
||||||
|
workflow_call:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: ${{ matrix.name }}
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- name: JVM / JS / Wasm / Native + API check
|
||||||
|
os: ubuntu-latest
|
||||||
|
tasks: jvmTest jsNodeTest wasmJsNodeTest nativeTest apiCheck
|
||||||
|
- name: iOS
|
||||||
|
os: macos-latest
|
||||||
|
tasks: iosSimulatorArm64Test
|
||||||
|
steps:
|
||||||
|
- name: Check out code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up JDK 21
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '21'
|
||||||
|
- name: Test
|
||||||
|
run: ./gradlew ${{ matrix.tasks }} --console=plain
|
||||||
2
.gitignore
vendored
@@ -9,6 +9,7 @@
|
|||||||
/.idea/assetWizardSettings.xml
|
/.idea/assetWizardSettings.xml
|
||||||
.DS_Store
|
.DS_Store
|
||||||
/build
|
/build
|
||||||
|
build/
|
||||||
/captures
|
/captures
|
||||||
.externalNativeBuild
|
.externalNativeBuild
|
||||||
.cxx
|
.cxx
|
||||||
@@ -16,3 +17,4 @@
|
|||||||
/.idea/compiler.xml
|
/.idea/compiler.xml
|
||||||
/.idea/jarRepositories.xml
|
/.idea/jarRepositories.xml
|
||||||
/.idea/deploymentTargetDropDown.xml
|
/.idea/deploymentTargetDropDown.xml
|
||||||
|
/.idea/
|
||||||
|
|||||||
125
.idea/codeStyles/Project.xml
generated
@@ -1,125 +0,0 @@
|
|||||||
<component name="ProjectCodeStyleConfiguration">
|
|
||||||
<code_scheme name="Project" version="173">
|
|
||||||
<JetCodeStyleSettings>
|
|
||||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
|
||||||
</JetCodeStyleSettings>
|
|
||||||
<MarkdownNavigatorCodeStyleSettings>
|
|
||||||
<option name="RIGHT_MARGIN" value="72" />
|
|
||||||
</MarkdownNavigatorCodeStyleSettings>
|
|
||||||
<codeStyleSettings language="XML">
|
|
||||||
<indentOptions>
|
|
||||||
<option name="CONTINUATION_INDENT_SIZE" value="4" />
|
|
||||||
</indentOptions>
|
|
||||||
<arrangement>
|
|
||||||
<rules>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>xmlns:android</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>xmlns:.*</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
<order>BY_NAME</order>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>.*:id</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>.*:name</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>name</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>style</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>.*</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>^$</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
<order>BY_NAME</order>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>.*</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
<order>ANDROID_ATTRIBUTE_ORDER</order>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
<section>
|
|
||||||
<rule>
|
|
||||||
<match>
|
|
||||||
<AND>
|
|
||||||
<NAME>.*</NAME>
|
|
||||||
<XML_ATTRIBUTE />
|
|
||||||
<XML_NAMESPACE>.*</XML_NAMESPACE>
|
|
||||||
</AND>
|
|
||||||
</match>
|
|
||||||
<order>BY_NAME</order>
|
|
||||||
</rule>
|
|
||||||
</section>
|
|
||||||
</rules>
|
|
||||||
</arrangement>
|
|
||||||
</codeStyleSettings>
|
|
||||||
<codeStyleSettings language="kotlin">
|
|
||||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
|
||||||
</codeStyleSettings>
|
|
||||||
</code_scheme>
|
|
||||||
</component>
|
|
||||||
5
.idea/codeStyles/codeStyleConfig.xml
generated
@@ -1,5 +0,0 @@
|
|||||||
<component name="ProjectCodeStyleConfiguration">
|
|
||||||
<state>
|
|
||||||
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
|
|
||||||
</state>
|
|
||||||
</component>
|
|
||||||
22
.idea/gradle.xml
generated
@@ -1,22 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
|
||||||
<component name="GradleSettings">
|
|
||||||
<option name="linkedExternalProjectsSettings">
|
|
||||||
<GradleProjectSettings>
|
|
||||||
<option name="testRunner" value="GRADLE" />
|
|
||||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
|
||||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
|
||||||
<option name="gradleJvm" value="11 (2)" />
|
|
||||||
<option name="modules">
|
|
||||||
<set>
|
|
||||||
<option value="$PROJECT_DIR$" />
|
|
||||||
<option value="$PROJECT_DIR$/app" />
|
|
||||||
<option value="$PROJECT_DIR$/treedatastructure" />
|
|
||||||
</set>
|
|
||||||
</option>
|
|
||||||
<option name="resolveModulePerSourceSet" value="false" />
|
|
||||||
</GradleProjectSettings>
|
|
||||||
</option>
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
9
.idea/misc.xml
generated
@@ -1,9 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" project-jdk-name="1.8" project-jdk-type="JavaSDK">
|
|
||||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
|
||||||
</component>
|
|
||||||
<component name="ProjectType">
|
|
||||||
<option name="id" value="Android" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="VcsDirectoryMappings">
|
|
||||||
<mapping directory="" vcs="Git" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
79
CHANGELOG.md
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
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.0.0]
|
||||||
|
|
||||||
|
A breaking release that cleans up the core API and enforces an explicit public surface.
|
||||||
|
|
||||||
|
### Changed (breaking)
|
||||||
|
- `TreeNode.treeIterator` is now a read-only `val` (set it via the constructor). Use
|
||||||
|
`iterator(order)` or `asSequence(order)` to traverse in a different order per call.
|
||||||
|
- `removeChild(child)` now only removes a **direct** child of the receiver (previously it removed
|
||||||
|
the node from its actual parent regardless). Use `child.detach()` to unhook a node from wherever
|
||||||
|
it lives.
|
||||||
|
- `addChild(child)` now throws `TreeNodeException` if `child` already has a parent or if the
|
||||||
|
attachment would create a cycle. Call `detach()` first to move a node.
|
||||||
|
- `clear()` no longer detaches the receiver from its own parent; it only removes its descendants.
|
||||||
|
- `path(descendant)` now returns `List<TreeNode<T>>?` (`null` when `descendant` is the root or not a
|
||||||
|
descendant) instead of throwing `TreeNodeException`.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `TreeNode.detach()` — removes a node from its parent.
|
||||||
|
- `TreeNode.iterator(order)` — a one-shot iterator in a specific order.
|
||||||
|
- Strict `explicitApi()` mode across all modules.
|
||||||
|
- New `tree-structure-compose` module: a `LazyTree` composable for Compose Multiplatform.
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
- `node.treeIterator = PostOrder; for (n in node) { … }` → `for (n in node.asSequence(PostOrder)) { … }`
|
||||||
|
- `root.removeChild(deepNode)` → `deepNode.detach()`
|
||||||
|
- `try { node.path(x) } catch (e: TreeNodeException) { … }` → `node.path(x)?.let { … }`
|
||||||
|
|
||||||
|
## [3.4.0]
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Lazy `Sequence` traversal: `asSequence(order)`, `preOrderSequence()`, `postOrderSequence()`,
|
||||||
|
`levelOrderSequence()` — composes with the Kotlin stdlib and short-circuits.
|
||||||
|
- Navigation extensions: `isLeaf`, `degree`, `root()`, `ancestors()`, `siblings()`, `leaves()`,
|
||||||
|
`descendants()`.
|
||||||
|
- Functional extensions: `findNode`, `filterNodes`, `anyNode`, `allNodes`, `countNodes`,
|
||||||
|
`foldNodes`, `mapValues`, `deepCopy`, `structurallyEquals` (all stack-safe).
|
||||||
|
- New optional modules published as separate artifacts:
|
||||||
|
- `tree-structure-serialization` — `kotlinx.serialization` support via a `TreeNodeDto`.
|
||||||
|
- `tree-structure-coroutines` — `Flow` traversal (`asFlow`, `preOrderFlow`, …).
|
||||||
|
- `CHANGELOG.md`, expanded README examples, and class-level KDoc (thread-safety / complexity).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- `nodeCount()`, `height()`, `clear()` and the post-order iterator are now iterative — deep or
|
||||||
|
degenerate (linear) trees no longer throw `StackOverflowError`.
|
||||||
|
- Migrated to Kotlin 2.x (K2 compiler) and introduced a Gradle version catalog.
|
||||||
|
- Build now uses `binary-compatibility-validator` (committed `.api` baselines) and Kover.
|
||||||
|
|
||||||
|
## [3.1.5]
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Removed a stray `println` in `TreeNode.removeChild()` that printed to stdout on every removal.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
- Deleted the `Example.ws.kts` worksheet and the `kotlin("script-runtime")` dependency from the
|
||||||
|
published JVM artifact, plus the leftover `ExampleUnitTest` template test.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Bumped `actions/checkout` v2 → v4 in CI workflows.
|
||||||
|
|
||||||
|
## [3.1.4]
|
||||||
|
- Updated Kotlin and JS dependencies; added the `wasmJs` target.
|
||||||
|
|
||||||
|
## [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
|
||||||
|
[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
|
||||||
|
[3.1.4]: https://github.com/AdrianKuta/Tree-Data-Structure/releases/tag/v3.1.4
|
||||||
|
[3.1.3]: https://github.com/AdrianKuta/Tree-Data-Structure/releases/tag/v3.1.3
|
||||||
216
README.md
@@ -1,9 +1,44 @@
|
|||||||
# Tree (Data Structure)
|
# Tree (Data Structure)
|
||||||
[](https://mvnrepository.com/artifact/com.github.adriankuta/tree-structure)
|
[](https://mvnrepository.com/artifact/com.github.adriankuta/tree-structure)
|
||||||
[](https://github.com/AdrianKuta/Design-Patterns-Kotlin/blob/master/LICENSE)
|
[](https://github.com/AdrianKuta/Tree-Data-Structure/blob/master/LICENSE)
|
||||||
[](https://circleci.com/gh/AdrianKuta/Tree-Data-Structure)
|
[](https://github.com/AdrianKuta/Tree-Data-Structure/actions/workflows/publishRelease.yml)
|
||||||
|
|
||||||
Simple implementation to store object in tree structure.
|
Lightweight Kotlin Multiplatform tree data structure for Kotlin and Java. Includes a small DSL, multiple traversal iterators, and pretty-print support.
|
||||||
|
|
||||||
|
- Kotlin Multiplatform (JVM, JS, Wasm, iOS, and Native host)
|
||||||
|
- Pre-order, Post-order, and Level-order iteration
|
||||||
|
- Lazy `Sequence` traversal that composes with the Kotlin stdlib (`map`/`filter`/`firstOrNull`…)
|
||||||
|
- Navigation helpers: `root()`, `ancestors()`, `siblings()`, `leaves()`, `descendants()`, `isLeaf`, `degree`
|
||||||
|
- Functional helpers: `findNode`, `filterNodes`, `anyNode`, `allNodes`, `foldNodes`, `mapValues`, `deepCopy`, `structurallyEquals`
|
||||||
|
- Stack-safe: traversal and `height()`/`nodeCount()`/`clear()` handle arbitrarily deep trees without `StackOverflowError`
|
||||||
|
- Simple DSL: tree { child(...) }
|
||||||
|
- Utilities: nodeCount(), height(), depth(), path(), prettyString(), clear(), removeChild()
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
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") // see badge above for the latest version
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Gradle (Groovy):
|
||||||
|
```groovy
|
||||||
|
dependencies {
|
||||||
|
implementation "com.github.adriankuta:tree-structure:4.0.0" // see badge above for the latest
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Maven:
|
||||||
|
```xml
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.adriankuta</groupId>
|
||||||
|
<artifactId>tree-structure</artifactId>
|
||||||
|
<version>4.0.0</version>
|
||||||
|
</dependency>
|
||||||
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@@ -25,19 +60,15 @@ europe.addChild(france)
|
|||||||
println(root.prettyString())
|
println(root.prettyString())
|
||||||
```
|
```
|
||||||
|
|
||||||
**Pretty Kotlin**
|
**Pretty Kotlin (DSL)**
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
val root =
|
val root = tree("World") {
|
||||||
tree("World") {
|
child("North America") { child("USA") }
|
||||||
child("North America") {
|
child("Europe") {
|
||||||
child("USA")
|
child("Poland")
|
||||||
}
|
child("Germany")
|
||||||
child("Europe") {
|
|
||||||
child("Poland")
|
|
||||||
child("Germany")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Java**
|
**Java**
|
||||||
@@ -58,8 +89,7 @@ europe.addChild(france);
|
|||||||
System.out.println(root.prettyString());
|
System.out.println(root.prettyString());
|
||||||
```
|
```
|
||||||
|
|
||||||
*Output:*
|
Output:
|
||||||
|
|
||||||
```
|
```
|
||||||
World
|
World
|
||||||
├── North America
|
├── North America
|
||||||
@@ -69,11 +99,157 @@ World
|
|||||||
└── France
|
└── France
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Traversal and utilities
|
||||||
|
```kotlin
|
||||||
|
val root = TreeNode("root")
|
||||||
|
// ... build your tree
|
||||||
|
|
||||||
## Download
|
// Choose iteration order per call (the default order is set in the constructor and is read-only)
|
||||||
|
for (node in root.asSequence(TreeNodeIterators.PostOrder)) println(node.value)
|
||||||
|
|
||||||
|
// Utilities
|
||||||
|
root.nodeCount() // number of descendants
|
||||||
|
root.height() // longest path to a leaf (in edges)
|
||||||
|
root.depth() // distance from current node to the root
|
||||||
|
val path = root.path(root.children.first()) // nodes from descendant up to root
|
||||||
|
|
||||||
|
// Mutations — removeChild removes a *direct* child; detach() unhooks a node from wherever it lives
|
||||||
|
val child = root.children.first()
|
||||||
|
root.removeChild(child) // child is now detached from root
|
||||||
|
root.clear() // remove all descendants of root
|
||||||
|
```
|
||||||
|
|
||||||
|
### Lazy traversal with Sequence
|
||||||
|
|
||||||
|
Traversal is exposed as a lazy `Sequence`, so it composes with the Kotlin standard library and
|
||||||
|
short-circuits (it never materializes the whole tree just to find one node):
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
val tree = tree("World") {
|
||||||
|
child("North America") { child("USA") }
|
||||||
|
child("Europe") {
|
||||||
|
child("Poland")
|
||||||
|
child("Germany")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pick an order explicitly — no need to mutate the node's state.
|
||||||
|
tree.preOrderSequence().map { it.value }.toList() // [World, North America, USA, Europe, Poland, Germany]
|
||||||
|
tree.levelOrderSequence().first { it.value == "USA" } // stops as soon as it's found
|
||||||
|
tree.asSequence(TreeNodeIterators.PostOrder).count() // 6
|
||||||
|
```
|
||||||
|
|
||||||
|
### Navigation
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
val usa = tree.findNode { it == "USA" }!!
|
||||||
|
|
||||||
|
usa.isLeaf // true
|
||||||
|
usa.depth() // 2
|
||||||
|
usa.root().value // "World"
|
||||||
|
usa.ancestors().map { it.value } // [North America, World]
|
||||||
|
tree.leaves().map { it.value } // [USA, Poland, Germany]
|
||||||
|
val europe = tree.findNode { it == "Europe" }!!
|
||||||
|
europe.children.first().siblings().map { it.value } // [Germany]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Functional operations
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
tree.anyNode { it == "Poland" } // true
|
||||||
|
tree.filterNodes { it.length > 5 } // nodes whose value is longer than 5 chars
|
||||||
|
tree.countNodes { it.startsWith("U") } // 1
|
||||||
|
|
||||||
|
// Transform values into a brand-new tree (the original is untouched); stack-safe.
|
||||||
|
val lengths: TreeNode<Int> = tree.mapValues { it.length }
|
||||||
|
|
||||||
|
// Deep copy + structural comparison.
|
||||||
|
val copy = tree.deepCopy()
|
||||||
|
tree.structurallyEquals(copy) // true (same values, same shape, different nodes)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Optional modules
|
||||||
|
|
||||||
|
The core `tree-structure` artifact has no third-party dependencies. Ecosystem integrations ship as
|
||||||
|
separate, opt-in artifacts that depend on the core.
|
||||||
|
|
||||||
|
### Serialization — `tree-structure-serialization`
|
||||||
|
|
||||||
|
`kotlinx.serialization` support. A `TreeNode` holds a parent back-reference (a cycle), so it cannot
|
||||||
|
be `@Serializable` directly — convert to/from the acyclic `TreeNodeDto` instead.
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
implementation("com.github.adriankuta:tree-structure-serialization:4.0.0")
|
||||||
|
```
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
val json = Json.encodeToString(tree.toDto())
|
||||||
|
val restored = Json.decodeFromString<TreeNodeDto<String>>(json).toTreeNode()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Coroutines — `tree-structure-coroutines`
|
||||||
|
|
||||||
|
Traverse a tree as a cold `Flow` (handy in coroutine/`ViewModel` pipelines).
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
implementation("com.github.adriankuta:tree-structure-coroutines:4.0.0")
|
||||||
|
```
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
tree.preOrderFlow().collect { println(it.value) }
|
||||||
|
tree.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:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
implementation("com.github.adriankuta:tree-structure-compose:4.0.0")
|
||||||
|
```
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
LazyTree(root) { node, depth, expanded, toggle ->
|
||||||
|
Row(Modifier.padding(start = (depth * 16).dp).clickable(onClick = toggle)) {
|
||||||
|
if (!node.isLeaf) Text(if (expanded) "▾ " else "▸ ")
|
||||||
|
Text(node.value.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Publishing to Maven Central (central.sonatype.com)
|
||||||
|
|
||||||
|
This project is configured to publish artifacts to Maven Central via the Sonatype Central Portal.
|
||||||
|
|
||||||
|
There are two supported ways to publish:
|
||||||
|
|
||||||
|
1) Via GitHub Actions (recommended)
|
||||||
|
- Create a GitHub Release (tag) in this repository. When a release is published, the workflow .github/workflows/publishRelease.yml runs automatically.
|
||||||
|
- The workflow uses the Gradle task publishToMavenCentral to upload artifacts through the Central Portal.
|
||||||
|
- Make sure these repository secrets are configured in GitHub:
|
||||||
|
- MAVEN_CENTRAL_USERNAME — Your Sonatype Central username (not email).
|
||||||
|
- MAVEN_CENTRAL_PASSWORD — Your Sonatype Central password or a token from central.sonatype.com.
|
||||||
|
- SIGNING_KEY — ASCII‑armored GPG private key (exported, single line; for in‑memory signing).
|
||||||
|
- SIGNING_PASSWORD — Passphrase for the key above.
|
||||||
|
- The workflow uses JDK 21 and publishes the version defined in build.gradle.kts.
|
||||||
|
|
||||||
|
2) Locally via Gradle
|
||||||
|
- Ensure you have a Sonatype Central account and that the groupId com.github.adriankuta is verified in central.sonatype.com (Namespace Rules → Verify).
|
||||||
|
- Export the same credentials/signing values as environment variables or pass them as Gradle properties:
|
||||||
|
- ORG_GRADLE_PROJECT_mavenCentralUsername
|
||||||
|
- ORG_GRADLE_PROJECT_mavenCentralPassword
|
||||||
|
- ORG_GRADLE_PROJECT_signingInMemoryKey
|
||||||
|
- ORG_GRADLE_PROJECT_signingInMemoryKeyPassword
|
||||||
|
- Then run:
|
||||||
|
- ./gradlew publishToMavenCentral
|
||||||
|
- For snapshot publishing, set -Psnapshot=true (the version is derived from PUBLISH_VERSION with -SNAPSHOT).
|
||||||
|
|
||||||
|
Notes
|
||||||
|
- Publishing is powered by the com.vanniktech.maven.publish Gradle plugin and Sonatype Central Portal (no legacy Nexus staging URLs needed).
|
||||||
|
- The plugin is configured to sign all publications. Coordinates and POM metadata are defined in build.gradle.kts.
|
||||||
|
- If using the combined task is preferred, you can also run publishAndReleaseToMavenCentral when automatic release is enabled; this repository currently uploads with publishToMavenCentral from CI.
|
||||||
|
|
||||||
implementation "com.github.adriankuta:tree-structure:$latest_versions"
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT License
|
MIT License
|
||||||
@@ -97,3 +273,5 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
SOFTWARE.
|
SOFTWARE.
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
theme: jekyll-theme-minimal
|
|
||||||
title: Tree Data Structure
|
|
||||||
logo: images/console_output.png
|
|
||||||
101
api/tree-structure.api
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
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 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 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 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 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 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/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;
|
||||||
|
}
|
||||||
|
|
||||||
1
app/.gitignore
vendored
@@ -1 +0,0 @@
|
|||||||
/build
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
apply plugin: 'com.android.application'
|
|
||||||
apply plugin: 'kotlin-android'
|
|
||||||
|
|
||||||
android {
|
|
||||||
compileSdkVersion 31
|
|
||||||
buildToolsVersion "31.0.0"
|
|
||||||
defaultConfig {
|
|
||||||
applicationId "com.github.adriankuta.treedatastructure"
|
|
||||||
minSdkVersion 15
|
|
||||||
targetSdkVersion 31
|
|
||||||
versionCode 1
|
|
||||||
versionName "1.0"
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
|
||||||
}
|
|
||||||
buildTypes {
|
|
||||||
release {
|
|
||||||
minifyEnabled false
|
|
||||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
implementation fileTree(dir: 'libs', include: ['*.jar'])
|
|
||||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
|
|
||||||
implementation 'androidx.appcompat:appcompat:1.3.1'
|
|
||||||
implementation 'androidx.core:core-ktx:1.6.0'
|
|
||||||
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
|
|
||||||
implementation 'com.github.adriankuta:tree-structure:1.2.3'
|
|
||||||
testImplementation 'junit:junit:4.13.2'
|
|
||||||
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
|
|
||||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
|
|
||||||
}
|
|
||||||
21
app/proguard-rules.pro
vendored
@@ -1,21 +0,0 @@
|
|||||||
# Add project specific ProGuard rules here.
|
|
||||||
# You can control the set of applied configuration files using the
|
|
||||||
# proguardFiles setting in build.gradle.
|
|
||||||
#
|
|
||||||
# For more details, see
|
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
|
||||||
|
|
||||||
# If your project uses WebView with JS, uncomment the following
|
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
|
||||||
# class:
|
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
|
||||||
# public *;
|
|
||||||
#}
|
|
||||||
|
|
||||||
# Uncomment this to preserve the line number information for
|
|
||||||
# debugging stack traces.
|
|
||||||
#-keepattributes SourceFile,LineNumberTable
|
|
||||||
|
|
||||||
# If you keep the line number information, uncomment this to
|
|
||||||
# hide the original source file name.
|
|
||||||
#-renamesourcefileattribute SourceFile
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package com.github.adriankuta.treedatastructure
|
|
||||||
|
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
|
|
||||||
import org.junit.Assert.*
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instrumented test, which will execute on an Android device.
|
|
||||||
*
|
|
||||||
* See [testing documentation](http://d.android.com/tools/testing).
|
|
||||||
*/
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
|
||||||
class ExampleInstrumentedTest {
|
|
||||||
@Test
|
|
||||||
fun useAppContext() {
|
|
||||||
// Context of the app under test.
|
|
||||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
|
||||||
assertEquals("com.github.adriankuta.treedatastructure", appContext.packageName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
package="com.github.adriankuta.treedatastructure">
|
|
||||||
|
|
||||||
<application
|
|
||||||
android:allowBackup="true"
|
|
||||||
android:icon="@mipmap/ic_launcher"
|
|
||||||
android:label="@string/app_name"
|
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
|
||||||
android:supportsRtl="true"
|
|
||||||
android:theme="@style/AppTheme">
|
|
||||||
<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>
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
package com.github.adriankuta.treedatastructure
|
|
||||||
|
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.util.Log
|
|
||||||
import com.github.adriankuta.datastructure.tree.tree
|
|
||||||
|
|
||||||
class MainActivity : AppCompatActivity() {
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
setContentView(R.layout.activity_main)
|
|
||||||
|
|
||||||
val root =
|
|
||||||
tree("World") {
|
|
||||||
child("North America") {
|
|
||||||
child("USA") {
|
|
||||||
child("LA")
|
|
||||||
child("New York")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
child("Europe") {
|
|
||||||
child("Poland")
|
|
||||||
child("Germany")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Log.d("DEBUG_TAG", root.prettyString())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:aapt="http://schemas.android.com/aapt"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
<path
|
|
||||||
android:fillType="evenOdd"
|
|
||||||
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
|
|
||||||
android:strokeWidth="1"
|
|
||||||
android:strokeColor="#00000000">
|
|
||||||
<aapt:attr name="android:fillColor">
|
|
||||||
<gradient
|
|
||||||
android:endX="78.5885"
|
|
||||||
android:endY="90.9159"
|
|
||||||
android:startX="48.7653"
|
|
||||||
android:startY="61.0927"
|
|
||||||
android:type="linear">
|
|
||||||
<item
|
|
||||||
android:color="#44000000"
|
|
||||||
android:offset="0.0" />
|
|
||||||
<item
|
|
||||||
android:color="#00000000"
|
|
||||||
android:offset="1.0" />
|
|
||||||
</gradient>
|
|
||||||
</aapt:attr>
|
|
||||||
</path>
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFF"
|
|
||||||
android:fillType="nonZero"
|
|
||||||
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
|
|
||||||
android:strokeWidth="1"
|
|
||||||
android:strokeColor="#00000000" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,170 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
<path
|
|
||||||
android:fillColor="#008577"
|
|
||||||
android:pathData="M0,0h108v108h-108z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M9,0L9,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,0L19,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M29,0L29,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M39,0L39,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M49,0L49,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M59,0L59,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M69,0L69,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M79,0L79,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M89,0L89,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M99,0L99,108"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,9L108,9"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,19L108,19"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,29L108,29"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,39L108,39"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,49L108,49"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,59L108,59"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,69L108,69"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,79L108,79"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,89L108,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,99L108,99"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,29L89,29"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,39L89,39"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,49L89,49"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,59L89,59"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,69L89,69"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,79L89,79"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M29,19L29,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M39,19L39,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M49,19L49,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M59,19L59,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M69,19L69,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M79,19L79,89"
|
|
||||||
android:strokeWidth="0.8"
|
|
||||||
android:strokeColor="#33FFFFFF" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
|
||||||
xmlns:tools="http://schemas.android.com/tools"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="match_parent"
|
|
||||||
tools:context=".MainActivity">
|
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:text="Hello World!"
|
|
||||||
app:layout_constraintBottom_toBottomOf="parent"
|
|
||||||
app:layout_constraintLeft_toLeftOf="parent"
|
|
||||||
app:layout_constraintRight_toRightOf="parent"
|
|
||||||
app:layout_constraintTop_toTopOf="parent" />
|
|
||||||
|
|
||||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background" />
|
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
</adaptive-icon>
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background" />
|
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
</adaptive-icon>
|
|
||||||
|
Before Width: | Height: | Size: 2.9 KiB |
|
Before Width: | Height: | Size: 4.8 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 6.2 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 8.9 KiB |
|
Before Width: | Height: | Size: 15 KiB |
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<resources>
|
|
||||||
<color name="colorPrimary">#008577</color>
|
|
||||||
<color name="colorPrimaryDark">#00574B</color>
|
|
||||||
<color name="colorAccent">#D81B60</color>
|
|
||||||
</resources>
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
<resources>
|
|
||||||
<string name="app_name">Tree Data Structure</string>
|
|
||||||
</resources>
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<resources>
|
|
||||||
|
|
||||||
<!-- Base application theme. -->
|
|
||||||
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
|
|
||||||
<!-- Customize your theme here. -->
|
|
||||||
<item name="colorPrimary">@color/colorPrimary</item>
|
|
||||||
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
|
|
||||||
<item name="colorAccent">@color/colorAccent</item>
|
|
||||||
</style>
|
|
||||||
|
|
||||||
</resources>
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package com.github.adriankuta.treedatastructure
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
import org.junit.Assert.*
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Example local unit test, which will execute on the development machine (host).
|
|
||||||
*
|
|
||||||
* See [testing documentation](http://d.android.com/tools/testing).
|
|
||||||
*/
|
|
||||||
class ExampleUnitTest {
|
|
||||||
@Test
|
|
||||||
fun addition_isCorrect() {
|
|
||||||
assertEquals(4, 2 + 2)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
32
build.gradle
@@ -1,32 +0,0 @@
|
|||||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
|
||||||
|
|
||||||
buildscript {
|
|
||||||
ext.kotlin_version = '1.5.30'
|
|
||||||
repositories {
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
dependencies {
|
|
||||||
classpath 'com.android.tools.build:gradle:7.0.2'
|
|
||||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
|
||||||
// NOTE: Do not place your application dependencies here; they belong
|
|
||||||
// in the individual module build.gradle files
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
plugins {
|
|
||||||
id("io.github.gradle-nexus.publish-plugin") version "1.1.0"
|
|
||||||
id("org.jetbrains.dokka") version "1.5.0"
|
|
||||||
}
|
|
||||||
|
|
||||||
allprojects {
|
|
||||||
repositories {
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
task clean(type: Delete) {
|
|
||||||
delete rootProject.buildDir
|
|
||||||
}
|
|
||||||
apply from: "${rootDir}/scripts/publish-root.gradle"
|
|
||||||
99
build.gradle.kts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
|
alias(libs.plugins.dokka)
|
||||||
|
alias(libs.plugins.mavenPublish)
|
||||||
|
alias(libs.plugins.binaryCompatibilityValidator)
|
||||||
|
alias(libs.plugins.kover)
|
||||||
|
signing
|
||||||
|
}
|
||||||
|
|
||||||
|
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 snapshot: String? by project
|
||||||
|
|
||||||
|
group = PUBLISH_GROUP_ID
|
||||||
|
version = if (snapshot.toBoolean()) "$PUBLISH_VERSION-SNAPSHOT" else PUBLISH_VERSION
|
||||||
|
|
||||||
|
mavenPublishing {
|
||||||
|
// Central Portal + auto release when we call publishAndReleaseToMavenCentral
|
||||||
|
publishToMavenCentral(automaticRelease = false)
|
||||||
|
signAllPublications()
|
||||||
|
|
||||||
|
coordinates(PUBLISH_GROUP_ID, PUBLISH_ARTIFACT_ID, version.toString())
|
||||||
|
|
||||||
|
pom {
|
||||||
|
name.set("Tree Data Structure")
|
||||||
|
description.set(
|
||||||
|
"Lightweight n-ary tree data structure for Kotlin Multiplatform (JVM, JS, Wasm, iOS, " +
|
||||||
|
"Native). DSL, pre/post/level-order traversal, lazy Sequence traversal, and pretty-print.",
|
||||||
|
)
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
explicitApi()
|
||||||
|
jvmToolchain(21)
|
||||||
|
|
||||||
|
jvm()
|
||||||
|
|
||||||
|
js(IR) {
|
||||||
|
browser()
|
||||||
|
nodejs()
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalWasmDsl::class)
|
||||||
|
wasmJs {
|
||||||
|
browser()
|
||||||
|
nodejs()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apple targets
|
||||||
|
iosX64()
|
||||||
|
iosArm64()
|
||||||
|
iosSimulatorArm64()
|
||||||
|
|
||||||
|
// Native host target
|
||||||
|
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 {
|
||||||
|
commonTest.dependencies {
|
||||||
|
implementation(kotlin("test"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1 @@
|
|||||||
# Project-wide Gradle settings.
|
|
||||||
# IDE (e.g. Android Studio) users:
|
|
||||||
# Gradle settings configured through the IDE *will override*
|
|
||||||
# any settings specified in this file.
|
|
||||||
# For more details on how to configure your build environment visit
|
|
||||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
|
||||||
# Specifies the JVM arguments used for the daemon process.
|
|
||||||
# The setting is particularly useful for tweaking memory settings.
|
|
||||||
org.gradle.jvmargs=-Xmx1536m
|
|
||||||
# When configured, Gradle will run in incubating parallel mode.
|
|
||||||
# This option should only be used with decoupled projects. More details, visit
|
|
||||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
|
||||||
# org.gradle.parallel=true
|
|
||||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
|
||||||
# Android operating system, and which are packaged with your app's APK
|
|
||||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
|
||||||
android.useAndroidX=true
|
|
||||||
# Automatically convert third-party libraries to use AndroidX
|
|
||||||
android.enableJetifier=true
|
|
||||||
# Kotlin code style for this project: "official" or "obsolete":
|
|
||||||
kotlin.code.style=official
|
kotlin.code.style=official
|
||||||
|
|||||||
24
gradle/libs.versions.toml
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
[versions]
|
||||||
|
kotlin = "2.1.0"
|
||||||
|
dokka = "1.9.20"
|
||||||
|
mavenPublish = "0.34.0"
|
||||||
|
binaryCompatibilityValidator = "0.16.3"
|
||||||
|
kover = "0.8.3"
|
||||||
|
coroutines = "1.9.0"
|
||||||
|
kotlinxSerialization = "1.7.3"
|
||||||
|
composeMultiplatform = "1.7.3"
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
|
||||||
|
kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||||
|
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" }
|
||||||
|
kover = { id = "org.jetbrains.kotlinx.kover", version.ref = "kover" }
|
||||||
|
composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "composeMultiplatform" }
|
||||||
|
composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
|
|
||||||
|
[libraries]
|
||||||
|
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" }
|
||||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
5
gradle/wrapper/gradle-wrapper.properties
vendored
@@ -1,6 +1,7 @@
|
|||||||
#Wed Jan 08 12:28:15 CET 2020
|
|
||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
|
|
||||||
|
|||||||
309
gradlew
vendored
@@ -1,78 +1,127 @@
|
|||||||
#!/usr/bin/env sh
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
|
||||||
##############################################################################
|
##############################################################################
|
||||||
##
|
#
|
||||||
## Gradle start up script for UN*X
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
##
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
##############################################################################
|
##############################################################################
|
||||||
|
|
||||||
# Attempt to set APP_HOME
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
# Resolve links: $0 may be a link
|
# Resolve links: $0 may be a link
|
||||||
PRG="$0"
|
app_path=$0
|
||||||
# Need this for relative symlinks.
|
|
||||||
while [ -h "$PRG" ] ; do
|
# Need this for daisy-chained symlinks.
|
||||||
ls=`ls -ld "$PRG"`
|
while
|
||||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
if expr "$link" : '/.*' > /dev/null; then
|
[ -h "$app_path" ]
|
||||||
PRG="$link"
|
do
|
||||||
else
|
ls=$( ls -ld "$app_path" )
|
||||||
PRG=`dirname "$PRG"`"/$link"
|
link=${ls#*' -> '}
|
||||||
fi
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
done
|
done
|
||||||
SAVED="`pwd`"
|
|
||||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
|
||||||
APP_HOME="`pwd -P`"
|
|
||||||
cd "$SAVED" >/dev/null
|
|
||||||
|
|
||||||
APP_NAME="Gradle"
|
# This is normally unused
|
||||||
APP_BASE_NAME=`basename "$0"`
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
DEFAULT_JVM_OPTS=""
|
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||||
|
|
||||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
MAX_FD="maximum"
|
MAX_FD=maximum
|
||||||
|
|
||||||
warn () {
|
warn () {
|
||||||
echo "$*"
|
echo "$*"
|
||||||
}
|
} >&2
|
||||||
|
|
||||||
die () {
|
die () {
|
||||||
echo
|
echo
|
||||||
echo "$*"
|
echo "$*"
|
||||||
echo
|
echo
|
||||||
exit 1
|
exit 1
|
||||||
}
|
} >&2
|
||||||
|
|
||||||
# OS specific support (must be 'true' or 'false').
|
# OS specific support (must be 'true' or 'false').
|
||||||
cygwin=false
|
cygwin=false
|
||||||
msys=false
|
msys=false
|
||||||
darwin=false
|
darwin=false
|
||||||
nonstop=false
|
nonstop=false
|
||||||
case "`uname`" in
|
case "$( uname )" in #(
|
||||||
CYGWIN* )
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
cygwin=true
|
Darwin* ) darwin=true ;; #(
|
||||||
;;
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
Darwin* )
|
NONSTOP* ) nonstop=true ;;
|
||||||
darwin=true
|
|
||||||
;;
|
|
||||||
MINGW* )
|
|
||||||
msys=true
|
|
||||||
;;
|
|
||||||
NONSTOP* )
|
|
||||||
nonstop=true
|
|
||||||
;;
|
|
||||||
esac
|
esac
|
||||||
|
|
||||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
# Determine the Java command to use to start the JVM.
|
# Determine the Java command to use to start the JVM.
|
||||||
if [ -n "$JAVA_HOME" ] ; then
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
else
|
else
|
||||||
JAVACMD="$JAVA_HOME/bin/java"
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
fi
|
fi
|
||||||
if [ ! -x "$JAVACMD" ] ; then
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
@@ -81,92 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the
|
|||||||
location of your Java installation."
|
location of your Java installation."
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
JAVACMD="java"
|
JAVACMD=java
|
||||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
location of your Java installation."
|
location of your Java installation."
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Increase the maximum file descriptors if we can.
|
# Increase the maximum file descriptors if we can.
|
||||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
MAX_FD_LIMIT=`ulimit -H -n`
|
case $MAX_FD in #(
|
||||||
if [ $? -eq 0 ] ; then
|
max*)
|
||||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
MAX_FD="$MAX_FD_LIMIT"
|
# shellcheck disable=SC2039,SC3045
|
||||||
fi
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
ulimit -n $MAX_FD
|
warn "Could not query maximum file descriptor limit"
|
||||||
if [ $? -ne 0 ] ; then
|
esac
|
||||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
case $MAX_FD in #(
|
||||||
fi
|
'' | soft) :;; #(
|
||||||
else
|
*)
|
||||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
fi
|
# shellcheck disable=SC2039,SC3045
|
||||||
fi
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
# For Darwin, add options to specify how the application appears in the dock
|
|
||||||
if $darwin; then
|
|
||||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
|
||||||
fi
|
|
||||||
|
|
||||||
# For Cygwin, switch paths to Windows format before running java
|
|
||||||
if $cygwin ; then
|
|
||||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
|
||||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
|
||||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
|
||||||
|
|
||||||
# We build the pattern for arguments to be converted via cygpath
|
|
||||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
|
||||||
SEP=""
|
|
||||||
for dir in $ROOTDIRSRAW ; do
|
|
||||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
|
||||||
SEP="|"
|
|
||||||
done
|
|
||||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
|
||||||
# Add a user-defined pattern to the cygpath arguments
|
|
||||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
|
||||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
|
||||||
fi
|
|
||||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
|
||||||
i=0
|
|
||||||
for arg in "$@" ; do
|
|
||||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
|
||||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
|
||||||
|
|
||||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
|
||||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
|
||||||
else
|
|
||||||
eval `echo args$i`="\"$arg\""
|
|
||||||
fi
|
|
||||||
i=$((i+1))
|
|
||||||
done
|
|
||||||
case $i in
|
|
||||||
(0) set -- ;;
|
|
||||||
(1) set -- "$args0" ;;
|
|
||||||
(2) set -- "$args0" "$args1" ;;
|
|
||||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
|
||||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
|
||||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
|
||||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
|
||||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
|
||||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
|
||||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
|
||||||
esac
|
esac
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Escape application args
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
save () {
|
# * args from the command line
|
||||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
# * the main class name
|
||||||
echo " "
|
# * -classpath
|
||||||
}
|
# * -D...appname settings
|
||||||
APP_ARGS=$(save "$@")
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
|
||||||
cd "$(dirname "$0")"
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
exec "$JAVACMD" "$@"
|
exec "$JAVACMD" "$@"
|
||||||
|
|||||||
56
gradlew.bat
vendored
@@ -1,4 +1,20 @@
|
|||||||
@if "%DEBUG%" == "" @echo off
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
@rem ##########################################################################
|
@rem ##########################################################################
|
||||||
@rem
|
@rem
|
||||||
@rem Gradle startup script for Windows
|
@rem Gradle startup script for Windows
|
||||||
@@ -9,19 +25,23 @@
|
|||||||
if "%OS%"=="Windows_NT" setlocal
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
set DIRNAME=%~dp0
|
set DIRNAME=%~dp0
|
||||||
if "%DIRNAME%" == "" set DIRNAME=.
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
set APP_BASE_NAME=%~n0
|
set APP_BASE_NAME=%~n0
|
||||||
set APP_HOME=%DIRNAME%
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
set DEFAULT_JVM_OPTS=
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
@rem Find java.exe
|
@rem Find java.exe
|
||||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
set JAVA_EXE=java.exe
|
set JAVA_EXE=java.exe
|
||||||
%JAVA_EXE% -version >NUL 2>&1
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
if "%ERRORLEVEL%" == "0" goto init
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
@@ -35,7 +55,7 @@ goto fail
|
|||||||
set JAVA_HOME=%JAVA_HOME:"=%
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
if exist "%JAVA_EXE%" goto init
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||||
@@ -45,38 +65,26 @@ echo location of your Java installation.
|
|||||||
|
|
||||||
goto fail
|
goto fail
|
||||||
|
|
||||||
:init
|
|
||||||
@rem Get command-line arguments, handling Windows variants
|
|
||||||
|
|
||||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
|
||||||
|
|
||||||
:win9xME_args
|
|
||||||
@rem Slurp the command line arguments.
|
|
||||||
set CMD_LINE_ARGS=
|
|
||||||
set _SKIP=2
|
|
||||||
|
|
||||||
:win9xME_args_slurp
|
|
||||||
if "x%~1" == "x" goto execute
|
|
||||||
|
|
||||||
set CMD_LINE_ARGS=%*
|
|
||||||
|
|
||||||
:execute
|
:execute
|
||||||
@rem Setup the command line
|
@rem Setup the command line
|
||||||
|
|
||||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
@rem Execute Gradle
|
@rem Execute Gradle
|
||||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||||
|
|
||||||
:end
|
:end
|
||||||
@rem End local scope for the variables with windows NT shell
|
@rem End local scope for the variables with windows NT shell
|
||||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
:fail
|
:fail
|
||||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
rem the _cmd.exe /c_ return code!
|
rem the _cmd.exe /c_ return code!
|
||||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
exit /b 1
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
:mainEnd
|
:mainEnd
|
||||||
if "%OS%"=="Windows_NT" endlocal
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 71 KiB |
1999
kotlin-js-store/yarn.lock
Normal file
@@ -1,86 +0,0 @@
|
|||||||
apply plugin: 'maven-publish'
|
|
||||||
apply plugin: 'signing'
|
|
||||||
apply plugin: 'org.jetbrains.dokka'
|
|
||||||
|
|
||||||
task androidSourcesJar(type: Jar) {
|
|
||||||
archiveClassifier.set('sources')
|
|
||||||
if (project.plugins.findPlugin("com.android.library")) {
|
|
||||||
from android.sourceSets.main.java.srcDirs
|
|
||||||
from android.sourceSets.main.kotlin.srcDirs
|
|
||||||
} else {
|
|
||||||
from sourceSets.main.java.srcDirs
|
|
||||||
from sourceSets.main.kotlin.srcDirs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.withType(dokkaHtmlPartial.getClass()).configureEach {
|
|
||||||
pluginsMapConfiguration.set(
|
|
||||||
["org.jetbrains.dokka.base.DokkaBase": """{ "separateInheritedMembers": true}"""]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
task javadocJar(type: Jar, dependsOn: dokkaJavadoc) {
|
|
||||||
archiveClassifier.set('javadoc')
|
|
||||||
from dokkaJavadoc.outputDirectory
|
|
||||||
}
|
|
||||||
|
|
||||||
artifacts {
|
|
||||||
archives androidSourcesJar
|
|
||||||
archives javadocJar
|
|
||||||
}
|
|
||||||
|
|
||||||
group = PUBLISH_GROUP_ID
|
|
||||||
version = PUBLISH_VERSION
|
|
||||||
|
|
||||||
afterEvaluate {
|
|
||||||
publishing {
|
|
||||||
publications {
|
|
||||||
release(MavenPublication) {
|
|
||||||
groupId PUBLISH_GROUP_ID
|
|
||||||
artifactId PUBLISH_ARTIFACT_ID
|
|
||||||
version PUBLISH_VERSION
|
|
||||||
if (project.plugins.findPlugin("com.android.library")) {
|
|
||||||
from components.release
|
|
||||||
} else {
|
|
||||||
from components.java
|
|
||||||
}
|
|
||||||
|
|
||||||
artifact androidSourcesJar
|
|
||||||
artifact javadocJar
|
|
||||||
|
|
||||||
pom {
|
|
||||||
name = PUBLISH_ARTIFACT_ID
|
|
||||||
description = 'Simple implementation to store object in tree structure.'
|
|
||||||
url = 'https://github.com/AdrianKuta/Tree-Data-Structure'
|
|
||||||
licenses {
|
|
||||||
license {
|
|
||||||
name = 'MIT License'
|
|
||||||
url = 'https://www.mit.edu/~amini/LICENSE.md'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
developers {
|
|
||||||
developer {
|
|
||||||
name = 'Adrian Kuta'
|
|
||||||
email = 'adrian.kuta93@gmail.com'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Version control info, if you're using GitHub, follow the format as seen here
|
|
||||||
scm {
|
|
||||||
connection = 'scm:git:github.com/AdrianKuta/Tree-Data-Structure.git'
|
|
||||||
developerConnection = 'scm:git:ssh://github.com/AdrianKuta/Tree-Data-Structure.git'
|
|
||||||
url = 'https://github.com/AdrianKuta/Tree-Data-Structure/tree/master'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
signing {
|
|
||||||
useInMemoryPgpKeys(
|
|
||||||
rootProject.ext["signing.keyId"],
|
|
||||||
rootProject.ext["signing.key"],
|
|
||||||
rootProject.ext["signing.password"],
|
|
||||||
)
|
|
||||||
sign publishing.publications
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
// Create variables with empty default values
|
|
||||||
ext["ossrhUsername"] = ''
|
|
||||||
ext["ossrhPassword"] = ''
|
|
||||||
ext["sonatypeStagingProfileId"] = ''
|
|
||||||
ext["signing.keyId"] = ''
|
|
||||||
ext["signing.password"] = ''
|
|
||||||
ext["signing.key"] = ''
|
|
||||||
ext["snapshot"] = ''
|
|
||||||
|
|
||||||
File secretPropsFile = project.rootProject.file('local.properties')
|
|
||||||
if (secretPropsFile.exists()) {
|
|
||||||
// Read local.properties file first if it exists
|
|
||||||
Properties p = new Properties()
|
|
||||||
new FileInputStream(secretPropsFile).withCloseable { is -> p.load(is) }
|
|
||||||
p.each { name, value -> ext[name] = value }
|
|
||||||
} else {
|
|
||||||
// Use system environment variables
|
|
||||||
ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME')
|
|
||||||
ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD')
|
|
||||||
ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID')
|
|
||||||
ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID')
|
|
||||||
ext["signing.password"] = System.getenv('SIGNING_PASSWORD')
|
|
||||||
ext["signing.key"] = System.getenv('SIGNING_KEY')
|
|
||||||
ext["snapshot"] = System.getenv('SNAPSHOT')
|
|
||||||
}
|
|
||||||
|
|
||||||
//if (snapshot) {
|
|
||||||
// ext["rootVersionName"] = Configuration.snapshotVersionName
|
|
||||||
//} else {
|
|
||||||
// ext["rootVersionName"] = Configuration.versionName
|
|
||||||
//}
|
|
||||||
|
|
||||||
// Set up Sonatype repository
|
|
||||||
nexusPublishing {
|
|
||||||
repositories {
|
|
||||||
sonatype {
|
|
||||||
stagingProfileId = sonatypeStagingProfileId
|
|
||||||
username = ossrhUsername
|
|
||||||
password = ossrhPassword
|
|
||||||
//version = rootVersionName
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
include ':app', ':treedatastructure'
|
|
||||||
rootProject.name='Tree Data Structure'
|
|
||||||
5
settings.gradle.kts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
rootProject.name = "tree-structure"
|
||||||
|
|
||||||
|
include(":tree-structure-serialization")
|
||||||
|
include(":tree-structure-coroutines")
|
||||||
|
include(":tree-structure-compose")
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package com.github.adriankuta.datastructure.tree
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
interface ChildDeclarationInterface<T> {
|
import kotlin.jvm.JvmSynthetic
|
||||||
|
|
||||||
|
public interface ChildDeclarationInterface<T> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method is used to easily create child in node.
|
* This method is used to easily create child in node.
|
||||||
@@ -18,5 +20,5 @@ interface ChildDeclarationInterface<T> {
|
|||||||
* @return New created TreeNode.
|
* @return New created TreeNode.
|
||||||
*/
|
*/
|
||||||
@JvmSynthetic
|
@JvmSynthetic
|
||||||
fun child(value: T, childDeclaration: ChildDeclaration<T>? = null): TreeNode<T>
|
public fun child(value: T, childDeclaration: ChildDeclaration<T>? = null): TreeNode<T>
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.exceptions.TreeNodeException
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.LevelOrderTreeIterator
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.PostOrderTreeIterator
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.PreOrderTreeIterator
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators.*
|
||||||
|
import kotlin.jvm.JvmSynthetic
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A node in a generic, mutable n-ary tree. Each node holds a [value], a reference to its [parent]
|
||||||
|
* and an ordered list of [children].
|
||||||
|
*
|
||||||
|
* Iterating a node (via [iterator], or the lazy [asSequence]/[preOrderSequence] extensions) visits
|
||||||
|
* the node and all of its descendants. Traversal and the [height]/[nodeCount]/[clear] helpers are
|
||||||
|
* implemented iteratively, so they are safe on arbitrarily deep trees.
|
||||||
|
*
|
||||||
|
* **Not thread-safe.** Nodes are mutable ([addChild]/[removeChild]/[clear] mutate the structure and
|
||||||
|
* parent pointers). Sharing a tree across threads requires external synchronization, and the tree
|
||||||
|
* must not be modified while it is being iterated.
|
||||||
|
*
|
||||||
|
* Equality is by reference (identity); use the `structurallyEquals` extension to compare two trees
|
||||||
|
* by value and shape.
|
||||||
|
*
|
||||||
|
* @param value the value stored in this node.
|
||||||
|
* @param treeIterator the default traversal order used by [iterator]. Prefer the
|
||||||
|
* `asSequence(order)` / `preOrderSequence()` extensions to choose an order without mutating state.
|
||||||
|
*/
|
||||||
|
public open class TreeNode<T>(public val value: T, public val treeIterator: TreeNodeIterators = PreOrder) : Iterable<TreeNode<T>>, ChildDeclarationInterface<T> {
|
||||||
|
|
||||||
|
private var _parent: TreeNode<T>? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The converse notion of a child, an immediate ancestor.
|
||||||
|
*/
|
||||||
|
public val parent: TreeNode<T>?
|
||||||
|
get() = _parent
|
||||||
|
|
||||||
|
private val _children = mutableListOf<TreeNode<T>>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A group of nodes with the same parent.
|
||||||
|
*/
|
||||||
|
public val children: List<TreeNode<T>>
|
||||||
|
get() = _children
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether the current tree node is the root of the tree
|
||||||
|
* @return `true` if the current tree node is root of the tree, `false` otherwise.
|
||||||
|
*/
|
||||||
|
public val isRoot: Boolean
|
||||||
|
get() = _parent == null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds [child] as a direct child of this node.
|
||||||
|
*
|
||||||
|
* @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 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 addChild(child: TreeNode<T>) {
|
||||||
|
if (child._parent != null) {
|
||||||
|
throw TreeNodeException("$child already has a parent; call detach() before re-attaching it.")
|
||||||
|
}
|
||||||
|
if (child === this) {
|
||||||
|
throw TreeNodeException("Adding $child here would create a cycle.")
|
||||||
|
}
|
||||||
|
// Only a node that already has its own subtree can contain `this` and thus form a cycle.
|
||||||
|
// Skipping this walk for leaves keeps building deep trees O(n) instead of O(n²).
|
||||||
|
if (child._children.isNotEmpty()) {
|
||||||
|
var ancestor: TreeNode<T>? = _parent
|
||||||
|
while (ancestor != null) {
|
||||||
|
if (ancestor === child) {
|
||||||
|
throw TreeNodeException("Adding $child here would create a cycle.")
|
||||||
|
}
|
||||||
|
ancestor = ancestor._parent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child._parent = this
|
||||||
|
_children.add(child)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detaches this node from its parent, removing it from the parent's [children].
|
||||||
|
*
|
||||||
|
* @return `true` if this node was attached and is now detached; `false` if it was already a root.
|
||||||
|
*/
|
||||||
|
public fun detach(): Boolean {
|
||||||
|
val currentParent = _parent ?: return false
|
||||||
|
currentParent._children.remove(this)
|
||||||
|
_parent = null
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
@JvmSynthetic
|
||||||
|
public override fun child(value: T, childDeclaration: ChildDeclaration<T>?): TreeNode<T> {
|
||||||
|
val newChild = TreeNode(value)
|
||||||
|
newChild._parent = this
|
||||||
|
if (childDeclaration != null)
|
||||||
|
newChild.childDeclaration()
|
||||||
|
_children.add(newChild)
|
||||||
|
return newChild
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes [child] from this node's direct [children], if present.
|
||||||
|
*
|
||||||
|
* This only removes a *direct* child of the receiver; it does not reach into other nodes. To
|
||||||
|
* remove a node from wherever it currently lives, call [detach] on it instead.
|
||||||
|
*
|
||||||
|
* @return `true` if [child] was a direct child and has been removed; `false` otherwise.
|
||||||
|
*/
|
||||||
|
public fun removeChild(child: TreeNode<T>): Boolean {
|
||||||
|
val removed = _children.remove(child)
|
||||||
|
if (removed) child._parent = null
|
||||||
|
return removed
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function go through tree and counts children. Root element is not counted.
|
||||||
|
* @return All child and nested child count.
|
||||||
|
*/
|
||||||
|
public fun nodeCount(): Int {
|
||||||
|
var count = 0
|
||||||
|
val stack = ArrayDeque<TreeNode<T>>()
|
||||||
|
stack.addAll(_children)
|
||||||
|
while (stack.isNotEmpty()) {
|
||||||
|
val node = stack.removeLast()
|
||||||
|
count++
|
||||||
|
stack.addAll(node._children)
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return The number of edges on the longest path between current node and a descendant leaf.
|
||||||
|
*/
|
||||||
|
public fun height(): Int {
|
||||||
|
var maxDepth = 0
|
||||||
|
val stack = ArrayDeque<Pair<TreeNode<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
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Distance is the number of edges along the shortest path between two nodes.
|
||||||
|
* @return The distance between current node and the root.
|
||||||
|
*/
|
||||||
|
public fun depth(): Int {
|
||||||
|
var depth = 0
|
||||||
|
var tempParent = parent
|
||||||
|
|
||||||
|
while (tempParent != null) {
|
||||||
|
depth++
|
||||||
|
tempParent = tempParent.parent
|
||||||
|
}
|
||||||
|
return depth
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the chain of nodes from [descendant] up to and including this node, or `null` if
|
||||||
|
* [descendant] is not a strict descendant of this node.
|
||||||
|
*
|
||||||
|
* @param descendant the node to walk up from.
|
||||||
|
* @return the path `[descendant, …, this]`, or `null` if [descendant] is the root or is not
|
||||||
|
* located in this node's subtree.
|
||||||
|
*/
|
||||||
|
public fun path(descendant: TreeNode<T>): List<TreeNode<T>>? {
|
||||||
|
if (descendant.isRoot) return null
|
||||||
|
val path = mutableListOf<TreeNode<T>>()
|
||||||
|
var node = descendant
|
||||||
|
path.add(node)
|
||||||
|
while (!node.isRoot) {
|
||||||
|
node = node.parent!!
|
||||||
|
path.add(node)
|
||||||
|
if (node == this) return path
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes every descendant of this node. Afterwards [children] is empty and all former
|
||||||
|
* descendants are detached (their parent is `null`). This node itself stays attached to its own
|
||||||
|
* parent.
|
||||||
|
*/
|
||||||
|
public fun clear() {
|
||||||
|
val descendants = ArrayDeque<TreeNode<T>>()
|
||||||
|
val stack = ArrayDeque<TreeNode<T>>()
|
||||||
|
stack.addAll(_children)
|
||||||
|
while (stack.isNotEmpty()) {
|
||||||
|
val node = stack.removeLast()
|
||||||
|
descendants.addLast(node)
|
||||||
|
stack.addAll(node._children)
|
||||||
|
}
|
||||||
|
descendants.forEach { node ->
|
||||||
|
node._parent = null
|
||||||
|
node._children.clear()
|
||||||
|
}
|
||||||
|
_children.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
public override fun toString(): String {
|
||||||
|
return value.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
public fun prettyString(): String {
|
||||||
|
val stringBuilder = StringBuilder()
|
||||||
|
print(stringBuilder, "", "")
|
||||||
|
return stringBuilder.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun print(stringBuilder: StringBuilder, prefix: String, childrenPrefix: String) {
|
||||||
|
stringBuilder.append(prefix)
|
||||||
|
stringBuilder.append(value)
|
||||||
|
stringBuilder.append('\n')
|
||||||
|
val childIterator = _children.iterator()
|
||||||
|
while (childIterator.hasNext()) {
|
||||||
|
val node = childIterator.next()
|
||||||
|
if (childIterator.hasNext()) {
|
||||||
|
node.print(stringBuilder, "$childrenPrefix├── ", "$childrenPrefix│ ")
|
||||||
|
} else {
|
||||||
|
node.print(stringBuilder, "$childrenPrefix└── ", "$childrenPrefix ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an iterator over this node and its descendants using the default [treeIterator] order.
|
||||||
|
* Use [iterator] with an explicit order, or the `asSequence(order)` extension, to traverse in a
|
||||||
|
* different order without changing this node's default.
|
||||||
|
*/
|
||||||
|
public override fun iterator(): Iterator<TreeNode<T>> = iterator(treeIterator)
|
||||||
|
|
||||||
|
/** Returns an iterator over this node and its descendants in the given [order]. */
|
||||||
|
public fun iterator(order: TreeNodeIterators): Iterator<TreeNode<T>> = when (order) {
|
||||||
|
PreOrder -> PreOrderTreeIterator(this)
|
||||||
|
PostOrder -> PostOrderTreeIterator(this)
|
||||||
|
LevelOrder -> LevelOrderTreeIterator(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import kotlin.jvm.JvmSynthetic
|
||||||
|
|
||||||
|
public typealias ChildDeclaration<T> = ChildDeclarationInterface<T>.() -> Unit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method can be used to initialize new tree.
|
||||||
|
* ```
|
||||||
|
* val root = tree("World") { ... }
|
||||||
|
* ```
|
||||||
|
* @param root Root element of new tree.
|
||||||
|
* @see [ChildDeclarationInterface.child]
|
||||||
|
*/
|
||||||
|
@JvmSynthetic
|
||||||
|
public inline fun <reified T> tree(
|
||||||
|
root: T,
|
||||||
|
defaultIterator: TreeNodeIterators = TreeNodeIterators.PreOrder,
|
||||||
|
childDeclaration: ChildDeclaration<T>
|
||||||
|
): TreeNode<T> {
|
||||||
|
val treeNode = TreeNode(root, defaultIterator)
|
||||||
|
treeNode.childDeclaration()
|
||||||
|
return treeNode
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
/** Returns the first node (pre-order) whose value matches [predicate], or `null`. Short-circuits. */
|
||||||
|
public fun <T> TreeNode<T>.findNode(predicate: (T) -> Boolean): TreeNode<T>? =
|
||||||
|
preOrderSequence().firstOrNull { predicate(it.value) }
|
||||||
|
|
||||||
|
/** All nodes (pre-order) whose value matches [predicate]. */
|
||||||
|
public fun <T> TreeNode<T>.filterNodes(predicate: (T) -> Boolean): List<TreeNode<T>> =
|
||||||
|
preOrderSequence().filter { predicate(it.value) }.toList()
|
||||||
|
|
||||||
|
/** `true` if any node's value matches [predicate]. Short-circuits. */
|
||||||
|
public fun <T> TreeNode<T>.anyNode(predicate: (T) -> Boolean): Boolean =
|
||||||
|
preOrderSequence().any { predicate(it.value) }
|
||||||
|
|
||||||
|
/** `true` if every node's value matches [predicate]. Short-circuits. */
|
||||||
|
public fun <T> TreeNode<T>.allNodes(predicate: (T) -> Boolean): Boolean =
|
||||||
|
preOrderSequence().all { predicate(it.value) }
|
||||||
|
|
||||||
|
/** Counts nodes whose value matches [predicate]. */
|
||||||
|
public fun <T> TreeNode<T>.countNodes(predicate: (T) -> Boolean): Int =
|
||||||
|
preOrderSequence().count { predicate(it.value) }
|
||||||
|
|
||||||
|
/** Folds [operation] over all nodes in pre-order, starting from [initial]. */
|
||||||
|
public fun <T, R> TreeNode<T>.foldNodes(initial: R, operation: (acc: R, node: TreeNode<T>) -> R): R =
|
||||||
|
preOrderSequence().fold(initial) { acc, node -> operation(acc, node) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a new tree with the same shape whose values are produced by [transform]. The original is
|
||||||
|
* left untouched. Stack-safe (iterative), so it handles arbitrarily deep trees.
|
||||||
|
*/
|
||||||
|
public fun <T, R> TreeNode<T>.mapValues(transform: (T) -> R): TreeNode<R> {
|
||||||
|
val newRoot = TreeNode(transform(value), treeIterator)
|
||||||
|
val stack = ArrayDeque<Pair<TreeNode<T>, TreeNode<R>>>()
|
||||||
|
stack.addLast(this to newRoot)
|
||||||
|
while (stack.isNotEmpty()) {
|
||||||
|
val (source, target) = stack.removeLast()
|
||||||
|
source.children.forEach { child ->
|
||||||
|
val mappedChild = TreeNode(transform(child.value), child.treeIterator)
|
||||||
|
target.addChild(mappedChild)
|
||||||
|
stack.addLast(child to mappedChild)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newRoot
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns an independent deep copy of this subtree (same values, same shape, new nodes). */
|
||||||
|
public fun <T> TreeNode<T>.deepCopy(): TreeNode<T> = mapValues { it }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Structural equality: `true` when [other] holds the same values in the same shape. Unlike
|
||||||
|
* [TreeNode]'s reference equality, this compares the entire subtree. Stack-safe.
|
||||||
|
*/
|
||||||
|
public fun <T> TreeNode<T>.structurallyEquals(other: TreeNode<T>): Boolean {
|
||||||
|
val stack = ArrayDeque<Pair<TreeNode<T>, TreeNode<T>>>()
|
||||||
|
stack.addLast(this to other)
|
||||||
|
while (stack.isNotEmpty()) {
|
||||||
|
val (a, b) = stack.removeLast()
|
||||||
|
if (a.value != b.value) return false
|
||||||
|
if (a.children.size != b.children.size) return false
|
||||||
|
for (i in a.children.indices) {
|
||||||
|
stack.addLast(a.children[i] to b.children[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
/** `true` when this node has no children. */
|
||||||
|
public val <T> TreeNode<T>.isLeaf: Boolean get() = children.isEmpty()
|
||||||
|
|
||||||
|
/** The number of direct children of this node. */
|
||||||
|
public val <T> TreeNode<T>.degree: Int get() = children.size
|
||||||
|
|
||||||
|
/** Walks up the parent chain and returns the topmost ancestor (the tree root). */
|
||||||
|
public fun <T> TreeNode<T>.root(): TreeNode<T> {
|
||||||
|
var node = this
|
||||||
|
var parent = node.parent
|
||||||
|
while (parent != null) {
|
||||||
|
node = parent
|
||||||
|
parent = node.parent
|
||||||
|
}
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The chain of ancestors from the immediate [parent] up to (and including) the root. */
|
||||||
|
public fun <T> TreeNode<T>.ancestors(): List<TreeNode<T>> {
|
||||||
|
val result = mutableListOf<TreeNode<T>>()
|
||||||
|
var parent = this.parent
|
||||||
|
while (parent != null) {
|
||||||
|
result.add(parent)
|
||||||
|
parent = parent.parent
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The other children of this node's parent (excludes this node). Empty for the root. */
|
||||||
|
public fun <T> TreeNode<T>.siblings(): List<TreeNode<T>> =
|
||||||
|
parent?.children?.filter { it !== this } ?: emptyList()
|
||||||
|
|
||||||
|
/** All leaf nodes in this subtree, in pre-order. */
|
||||||
|
public fun <T> TreeNode<T>.leaves(): List<TreeNode<T>> =
|
||||||
|
preOrderSequence().filter { it.isLeaf }.toList()
|
||||||
|
|
||||||
|
/** All nodes in this subtree except this node, in pre-order. */
|
||||||
|
public fun <T> TreeNode<T>.descendants(): List<TreeNode<T>> =
|
||||||
|
preOrderSequence().filter { it !== this }.toList()
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.LevelOrderTreeIterator
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.PostOrderTreeIterator
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.PreOrderTreeIterator
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lazily traverses this subtree in the given [order] as a [Sequence], without forcing the whole
|
||||||
|
* traversal up front. Pairs with the Kotlin stdlib, e.g.
|
||||||
|
* `root.asSequence().map { it.value }.firstOrNull { it == target }`.
|
||||||
|
*/
|
||||||
|
public fun <T> TreeNode<T>.asSequence(
|
||||||
|
order: TreeNodeIterators = TreeNodeIterators.PreOrder,
|
||||||
|
): Sequence<TreeNode<T>> {
|
||||||
|
val self = this
|
||||||
|
return when (order) {
|
||||||
|
TreeNodeIterators.PreOrder -> Sequence { PreOrderTreeIterator(self) }
|
||||||
|
TreeNodeIterators.PostOrder -> Sequence { PostOrderTreeIterator(self) }
|
||||||
|
TreeNodeIterators.LevelOrder -> Sequence { LevelOrderTreeIterator(self) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lazy pre-order traversal as a [Sequence]. */
|
||||||
|
public fun <T> TreeNode<T>.preOrderSequence(): Sequence<TreeNode<T>> = asSequence(TreeNodeIterators.PreOrder)
|
||||||
|
|
||||||
|
/** Lazy post-order traversal as a [Sequence]. */
|
||||||
|
public fun <T> TreeNode<T>.postOrderSequence(): Sequence<TreeNode<T>> = asSequence(TreeNodeIterators.PostOrder)
|
||||||
|
|
||||||
|
/** Lazy level-order (breadth-first) traversal as a [Sequence]. */
|
||||||
|
public fun <T> TreeNode<T>.levelOrderSequence(): Sequence<TreeNode<T>> = asSequence(TreeNodeIterators.LevelOrder)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.exceptions
|
||||||
|
|
||||||
|
import kotlin.jvm.JvmOverloads
|
||||||
|
|
||||||
|
public class TreeNodeException @JvmOverloads constructor(message: String? = null, cause: Throwable? = null) :
|
||||||
|
RuntimeException(message, cause)
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.iterators
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.TreeNode
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tree is iterated by using `Level-order Traversal Algorithm"
|
||||||
|
* In level-order traversal we iterating nodes level by level,
|
||||||
|
* starting from root, and going deeper and deeper in tree.
|
||||||
|
* ```
|
||||||
|
* E.g.
|
||||||
|
* 1
|
||||||
|
* / | \
|
||||||
|
* / | \
|
||||||
|
* 2 3 4
|
||||||
|
* / \ / | \
|
||||||
|
* 5 6 7 8 9
|
||||||
|
* / / | \
|
||||||
|
* 10 11 12 13
|
||||||
|
*
|
||||||
|
* Output: 1 2 3 4 5 6 7 8 9 10 11 12 13
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public class LevelOrderTreeIterator<T>(root: TreeNode<T>) : Iterator<TreeNode<T>> {
|
||||||
|
|
||||||
|
private val stack = ArrayDeque<TreeNode<T>>()
|
||||||
|
|
||||||
|
init {
|
||||||
|
stack.addLast(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
public override fun hasNext(): Boolean = stack.isNotEmpty()
|
||||||
|
|
||||||
|
public override fun next(): TreeNode<T> {
|
||||||
|
val node = stack.removeFirst()
|
||||||
|
node.children
|
||||||
|
.forEach { stack.addLast(it) }
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.iterators
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.TreeNode
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tree is iterated by using `Post-order Traversal Algorithm"
|
||||||
|
* In post-order traversal, we starting from most left child.
|
||||||
|
* First visit all children of parent, then parent.
|
||||||
|
* ```
|
||||||
|
* E.g.
|
||||||
|
* 1
|
||||||
|
* / | \
|
||||||
|
* / | \
|
||||||
|
* 2 3 4
|
||||||
|
* / \ / | \
|
||||||
|
* 5 6 7 8 9
|
||||||
|
* / / | \
|
||||||
|
* 10 11 12 13
|
||||||
|
*
|
||||||
|
* Output: 10 5 11 12 13 6 2 3 7 8 9 4 1
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public class PostOrderTreeIterator<T>(root: TreeNode<T>) : Iterator<TreeNode<T>> {
|
||||||
|
|
||||||
|
private val result = ArrayDeque<TreeNode<T>>()
|
||||||
|
|
||||||
|
init {
|
||||||
|
// Iterative post-order: pop a node, prepend it to `result`, then push its children
|
||||||
|
// left-to-right. Reading `result` front-to-back yields post-order — without the deep
|
||||||
|
// recursion that overflowed the stack on degenerate (linear) trees.
|
||||||
|
val stack = ArrayDeque<TreeNode<T>>()
|
||||||
|
stack.addLast(root)
|
||||||
|
while (stack.isNotEmpty()) {
|
||||||
|
val node = stack.removeLast()
|
||||||
|
result.addFirst(node)
|
||||||
|
node.children.forEach { stack.addLast(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override fun hasNext(): Boolean = result.isNotEmpty()
|
||||||
|
|
||||||
|
public override fun next(): TreeNode<T> = result.removeFirst()
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.iterators
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.TreeNode
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tree is iterated by using `Pre-order Traversal Algorithm"
|
||||||
|
* The pre-order traversal is a topologically sorted one,
|
||||||
|
* because a parent node is processed before any of its child nodes is done.
|
||||||
|
* ```
|
||||||
|
* E.g.
|
||||||
|
* 1
|
||||||
|
* / | \
|
||||||
|
* / | \
|
||||||
|
* 2 3 4
|
||||||
|
* / \ / | \
|
||||||
|
* 5 6 7 8 9
|
||||||
|
* / / | \
|
||||||
|
* 10 11 12 13
|
||||||
|
*
|
||||||
|
* Output: 1 2 5 10 6 11 12 13 3 4 7 8 9
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
public class PreOrderTreeIterator<T>(root: TreeNode<T>) : Iterator<TreeNode<T>> {
|
||||||
|
|
||||||
|
private val stack = ArrayDeque<TreeNode<T>>()
|
||||||
|
|
||||||
|
init {
|
||||||
|
stack.addLast(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
public override fun hasNext(): Boolean = stack.isNotEmpty()
|
||||||
|
|
||||||
|
public override fun next(): TreeNode<T> {
|
||||||
|
val node = stack.removeLast()
|
||||||
|
node.children
|
||||||
|
.asReversed()
|
||||||
|
.forEach { stack.addLast(it) }
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.iterators
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @see PreOrder
|
||||||
|
* @see PostOrder
|
||||||
|
* @see LevelOrder
|
||||||
|
*/
|
||||||
|
public enum class TreeNodeIterators {
|
||||||
|
/**
|
||||||
|
* Tree is iterated by using `Pre-order Traversal Algorithm"
|
||||||
|
* The pre-order traversal is a topologically sorted one,
|
||||||
|
* because a parent node is processed before any of its child nodes is done.
|
||||||
|
* ```
|
||||||
|
* E.g.
|
||||||
|
* 1
|
||||||
|
* / | \
|
||||||
|
* / | \
|
||||||
|
* 2 3 4
|
||||||
|
* / \ / | \
|
||||||
|
* 5 6 7 8 9
|
||||||
|
* / / | \
|
||||||
|
* 10 11 12 13
|
||||||
|
*
|
||||||
|
* Output: 1 2 5 10 6 11 12 13 3 4 7 8 9
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
PreOrder,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tree is iterated by using `Post-order Traversal Algorithm"
|
||||||
|
* In post-order traversal, we starting from most left child.
|
||||||
|
* First visit all children of parent, then parent.
|
||||||
|
* ```
|
||||||
|
* E.g.
|
||||||
|
* 1
|
||||||
|
* / | \
|
||||||
|
* / | \
|
||||||
|
* 2 3 4
|
||||||
|
* / \ / | \
|
||||||
|
* 5 6 7 8 9
|
||||||
|
* / / | \
|
||||||
|
* 10 11 12 13
|
||||||
|
*
|
||||||
|
* Output: 10 5 11 12 13 6 2 3 7 8 9 4 1
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
PostOrder,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tree is iterated by using `Level-order Traversal Algorithm"
|
||||||
|
* In level-order traversal we iterating nodes level by level,
|
||||||
|
* starting from root, and going deeper and deeper in tree.
|
||||||
|
* ```
|
||||||
|
* E.g.
|
||||||
|
* 1
|
||||||
|
* / | \
|
||||||
|
* / | \
|
||||||
|
* 2 3 4
|
||||||
|
* / \ / | \
|
||||||
|
* 5 6 7 8 9
|
||||||
|
* / / | \
|
||||||
|
* 10 11 12 13
|
||||||
|
*
|
||||||
|
* Output: 1 2 3 4 5 6 7 8 9 10 11 12 13
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
LevelOrder
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
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.assertNotSame
|
||||||
|
import kotlin.test.assertNull
|
||||||
|
import kotlin.test.assertSame
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class TreeNodeFunctionalTest {
|
||||||
|
|
||||||
|
private fun sample() = tree(1) {
|
||||||
|
child(2) {
|
||||||
|
child(4)
|
||||||
|
child(5)
|
||||||
|
}
|
||||||
|
child(3) {
|
||||||
|
child(6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun findNode() {
|
||||||
|
assertEquals(6, sample().findNode { it == 6 }?.value)
|
||||||
|
assertNull(sample().findNode { it == 99 })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun filterNodes() =
|
||||||
|
assertContentEquals(listOf(2, 4, 6), sample().filterNodes { it % 2 == 0 }.map { it.value })
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun anyNode() {
|
||||||
|
assertTrue(sample().anyNode { it == 6 })
|
||||||
|
assertFalse(sample().anyNode { it == 99 })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun allNodes() {
|
||||||
|
assertTrue(sample().allNodes { it > 0 })
|
||||||
|
assertFalse(sample().allNodes { it < 5 })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun countNodes() = assertEquals(3, sample().countNodes { it > 3 })
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun foldNodes() = assertEquals(21, sample().foldNodes(0) { acc, node -> acc + node.value })
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun mapPreservesStructureAndTransformsValues() {
|
||||||
|
val mapped = sample().mapValues { it * 10 }
|
||||||
|
assertContentEquals(
|
||||||
|
listOf(10, 20, 40, 50, 30, 60),
|
||||||
|
mapped.preOrderSequence().map { it.value }.toList(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun deepCopyIsStructurallyEqualButDistinct() {
|
||||||
|
val original = sample()
|
||||||
|
val copy = original.deepCopy()
|
||||||
|
assertNotSame(original, copy)
|
||||||
|
assertTrue(original.structurallyEquals(copy))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun structurallyEqualsDistinguishesByValueAndShape() {
|
||||||
|
assertTrue(sample().structurallyEquals(sample()))
|
||||||
|
val different = tree(1) {
|
||||||
|
child(2) { child(4) }
|
||||||
|
child(3) { child(6) }
|
||||||
|
}
|
||||||
|
assertFalse(sample().structurallyEquals(different))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
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.assertSame
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class TreeNodeNavigationTest {
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
init {
|
||||||
|
root.addChild(n2)
|
||||||
|
root.addChild(n3)
|
||||||
|
n2.addChild(n4)
|
||||||
|
n2.addChild(n5)
|
||||||
|
n3.addChild(n6)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun isLeaf() {
|
||||||
|
assertTrue(n4.isLeaf)
|
||||||
|
assertFalse(root.isLeaf)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun degree() {
|
||||||
|
assertEquals(2, root.degree)
|
||||||
|
assertEquals(0, n4.degree)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun root() {
|
||||||
|
assertSame(root, n6.root())
|
||||||
|
assertSame(root, root.root())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ancestors() {
|
||||||
|
assertContentEquals(listOf(n2, root), n4.ancestors())
|
||||||
|
assertContentEquals(emptyList(), root.ancestors())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun siblings() {
|
||||||
|
assertContentEquals(listOf(n5), n4.siblings())
|
||||||
|
assertContentEquals(emptyList(), root.siblings())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun leaves() {
|
||||||
|
assertContentEquals(listOf(n4, n5, n6), root.leaves())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun descendants() {
|
||||||
|
assertContentEquals(listOf(n2, n4, n5, n3, n6), root.descendants())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContentEquals
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class TreeNodeSequenceTest {
|
||||||
|
|
||||||
|
private fun sample() = tree(1) {
|
||||||
|
child(2) {
|
||||||
|
child(4)
|
||||||
|
child(5)
|
||||||
|
}
|
||||||
|
child(3) {
|
||||||
|
child(6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun preOrderSequence() =
|
||||||
|
assertContentEquals(listOf(1, 2, 4, 5, 3, 6), sample().preOrderSequence().map { it.value }.toList())
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun postOrderSequence() =
|
||||||
|
assertContentEquals(listOf(4, 5, 2, 6, 3, 1), sample().postOrderSequence().map { it.value }.toList())
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun levelOrderSequence() =
|
||||||
|
assertContentEquals(listOf(1, 2, 3, 4, 5, 6), sample().levelOrderSequence().map { it.value }.toList())
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun asSequenceDefaultsToPreOrder() =
|
||||||
|
assertContentEquals(listOf(1, 2, 4, 5, 3, 6), sample().asSequence().map { it.value }.toList())
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun asSequenceHonorsExplicitOrder() =
|
||||||
|
assertContentEquals(
|
||||||
|
listOf(1, 2, 3, 4, 5, 6),
|
||||||
|
sample().asSequence(TreeNodeIterators.LevelOrder).map { it.value }.toList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sequenceShortCircuitsLazily() =
|
||||||
|
assertEquals(4, sample().preOrderSequence().map { it.value }.first { it == 4 })
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A deep, degenerate (linear) tree must not overflow the call stack. These tests build a chain
|
||||||
|
* thousands of nodes deep — recursive implementations of [TreeNode.height], [TreeNode.nodeCount]
|
||||||
|
* and the post-order iterator blow the stack here, so they pin the iterative rewrites.
|
||||||
|
*/
|
||||||
|
class TreeNodeStackSafetyTest {
|
||||||
|
|
||||||
|
private val depth = 50_000
|
||||||
|
|
||||||
|
private fun deepChain(): TreeNode<Int> {
|
||||||
|
val root = TreeNode(0)
|
||||||
|
var current = root
|
||||||
|
for (i in 1..depth) {
|
||||||
|
val child = TreeNode(i)
|
||||||
|
current.addChild(child)
|
||||||
|
current = child
|
||||||
|
}
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun heightDoesNotOverflowOnDeepTree() {
|
||||||
|
assertEquals(depth, deepChain().height())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nodeCountDoesNotOverflowOnDeepTree() {
|
||||||
|
// nodeCount() excludes the root, so a chain of `depth` extra nodes counts as `depth`.
|
||||||
|
assertEquals(depth, deepChain().nodeCount())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun postOrderIterationDoesNotOverflowOnDeepTree() {
|
||||||
|
assertEquals(depth + 1, deepChain().asSequence(TreeNodeIterators.PostOrder).count())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun preOrderIterationDoesNotOverflowOnDeepTree() {
|
||||||
|
assertEquals(depth + 1, deepChain().asSequence(TreeNodeIterators.PreOrder).count())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContentEquals
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFalse
|
||||||
|
import kotlin.test.assertNull
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class TreeNodeTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun removeNodeTest() {
|
||||||
|
val root = TreeNode("Root")
|
||||||
|
val beveragesNode = TreeNode("Beverages")
|
||||||
|
val curdNode = TreeNode("Curd")
|
||||||
|
root.addChild(beveragesNode)
|
||||||
|
root.addChild(curdNode)
|
||||||
|
|
||||||
|
val teaNode = TreeNode("tea")
|
||||||
|
val coffeeNode = TreeNode("coffee")
|
||||||
|
val milkShakeNode = TreeNode("Milk Shake")
|
||||||
|
beveragesNode.addChild(teaNode)
|
||||||
|
beveragesNode.addChild(coffeeNode)
|
||||||
|
beveragesNode.addChild(milkShakeNode)
|
||||||
|
|
||||||
|
val gingerTeaNode = TreeNode("ginger tea")
|
||||||
|
val normalTeaNode = TreeNode("normal tea")
|
||||||
|
teaNode.addChild(gingerTeaNode)
|
||||||
|
teaNode.addChild(normalTeaNode)
|
||||||
|
|
||||||
|
val yogurtNode = TreeNode("yogurt")
|
||||||
|
val lassiNode = TreeNode("lassi")
|
||||||
|
curdNode.addChild(yogurtNode)
|
||||||
|
curdNode.addChild(lassiNode)
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"Root\n" +
|
||||||
|
"├── Beverages\n" +
|
||||||
|
"│ ├── tea\n" +
|
||||||
|
"│ │ ├── ginger tea\n" +
|
||||||
|
"│ │ └── normal tea\n" +
|
||||||
|
"│ ├── coffee\n" +
|
||||||
|
"│ └── Milk Shake\n" +
|
||||||
|
"└── Curd\n" +
|
||||||
|
" ├── yogurt\n" +
|
||||||
|
" └── lassi\n",
|
||||||
|
root.prettyString(),
|
||||||
|
"Pretty print test"
|
||||||
|
)
|
||||||
|
|
||||||
|
root.removeChild(curdNode)
|
||||||
|
gingerTeaNode.detach()
|
||||||
|
assertEquals(
|
||||||
|
"Root\n" +
|
||||||
|
"└── Beverages\n" +
|
||||||
|
" ├── tea\n" +
|
||||||
|
" │ └── normal tea\n" +
|
||||||
|
" ├── coffee\n" +
|
||||||
|
" └── Milk Shake\n",
|
||||||
|
root.prettyString(),
|
||||||
|
"Remove node test"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun removeChildReturnsTrueWhenPresentFalseOtherwise() {
|
||||||
|
val root = TreeNode("Root")
|
||||||
|
val child = TreeNode("Child")
|
||||||
|
root.addChild(child)
|
||||||
|
|
||||||
|
assertTrue(root.removeChild(child), "Removing a present child returns true")
|
||||||
|
assertFalse(root.removeChild(child), "Removing an already-removed child returns false")
|
||||||
|
assertNull(child.parent, "Removed child is detached from its parent")
|
||||||
|
assertEquals(emptyList(), root.children)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun clearTest() {
|
||||||
|
val root = TreeNode("Root")
|
||||||
|
val beveragesNode = TreeNode("Beverages")
|
||||||
|
val curdNode = TreeNode("Curd")
|
||||||
|
root.addChild(beveragesNode)
|
||||||
|
root.addChild(curdNode)
|
||||||
|
|
||||||
|
val teaNode = TreeNode("tea")
|
||||||
|
val coffeeNode = TreeNode("coffee")
|
||||||
|
val milkShakeNode = TreeNode("Milk Shake")
|
||||||
|
beveragesNode.addChild(teaNode)
|
||||||
|
beveragesNode.addChild(coffeeNode)
|
||||||
|
beveragesNode.addChild(milkShakeNode)
|
||||||
|
|
||||||
|
val gingerTeaNode = TreeNode("ginger tea")
|
||||||
|
val normalTeaNode = TreeNode("normal tea")
|
||||||
|
teaNode.addChild(gingerTeaNode)
|
||||||
|
teaNode.addChild(normalTeaNode)
|
||||||
|
|
||||||
|
val yogurtNode = TreeNode("yogurt")
|
||||||
|
val lassiNode = TreeNode("lassi")
|
||||||
|
curdNode.addChild(yogurtNode)
|
||||||
|
curdNode.addChild(lassiNode)
|
||||||
|
|
||||||
|
root.clear()
|
||||||
|
assertEquals(root.children, emptyList())
|
||||||
|
assertEquals(beveragesNode.children, emptyList())
|
||||||
|
assertEquals(curdNode.children, emptyList())
|
||||||
|
assertEquals(teaNode.children, emptyList())
|
||||||
|
assertEquals(coffeeNode.children, emptyList())
|
||||||
|
assertEquals(milkShakeNode.children, emptyList())
|
||||||
|
assertEquals(gingerTeaNode.children, emptyList())
|
||||||
|
assertEquals(normalTeaNode.children, emptyList())
|
||||||
|
assertEquals(yogurtNode.children, emptyList())
|
||||||
|
assertEquals(lassiNode.children, emptyList())
|
||||||
|
|
||||||
|
assertNull(root.parent)
|
||||||
|
assertNull(beveragesNode.parent)
|
||||||
|
assertNull(curdNode.parent)
|
||||||
|
assertNull(teaNode.parent)
|
||||||
|
assertNull(coffeeNode.parent)
|
||||||
|
assertNull(milkShakeNode.parent)
|
||||||
|
assertNull(gingerTeaNode.parent)
|
||||||
|
assertNull(normalTeaNode.parent)
|
||||||
|
assertNull(yogurtNode.parent)
|
||||||
|
assertNull(lassiNode.parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun kotlinExtTest() {
|
||||||
|
val root = TreeNode("World")
|
||||||
|
val northA = TreeNode("North America")
|
||||||
|
val europe = TreeNode("Europe")
|
||||||
|
root.addChild(northA)
|
||||||
|
root.addChild(europe)
|
||||||
|
|
||||||
|
val usa = TreeNode("USA")
|
||||||
|
northA.addChild(usa)
|
||||||
|
|
||||||
|
val poland = TreeNode("Poland")
|
||||||
|
val france = TreeNode("France")
|
||||||
|
europe.addChild(poland)
|
||||||
|
europe.addChild(france)
|
||||||
|
|
||||||
|
val rootExt = tree("World") {
|
||||||
|
child("North America") {
|
||||||
|
child("USA")
|
||||||
|
}
|
||||||
|
child("Europe") {
|
||||||
|
child("Poland")
|
||||||
|
child("France")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(root.prettyString(), rootExt.prettyString())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun preOrderIteratorTest() {
|
||||||
|
val tree = tree("F") {
|
||||||
|
child("B") {
|
||||||
|
child("A")
|
||||||
|
child("D") {
|
||||||
|
child("C")
|
||||||
|
child("E")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child("G") {
|
||||||
|
child("I") {
|
||||||
|
child("H")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val expectedPreOrder = listOf("F", "B", "A", "D", "C", "E", "G", "I", "H")
|
||||||
|
assertContentEquals(expectedPreOrder, tree.toList().map { it.toString() })
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
fun postOrderIteratorTest() {
|
||||||
|
val tree = tree("A", TreeNodeIterators.PostOrder) {
|
||||||
|
child("B") {
|
||||||
|
child("E")
|
||||||
|
}
|
||||||
|
child("C")
|
||||||
|
child("D") {
|
||||||
|
child("F")
|
||||||
|
child("G")
|
||||||
|
child("H")
|
||||||
|
child("I")
|
||||||
|
child("J")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val expectedPreOrder = listOf("E", "B", "C", "F", "G", "H", "I", "J", "D", "A")
|
||||||
|
assertContentEquals(expectedPreOrder, tree.toList().map { it.toString() })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun secondPostOrderIteratorTest() {
|
||||||
|
val tree = tree(1, TreeNodeIterators.PostOrder) {
|
||||||
|
child(2) {
|
||||||
|
child(5) {
|
||||||
|
child(10)
|
||||||
|
}
|
||||||
|
child(6) {
|
||||||
|
child(11)
|
||||||
|
child(12)
|
||||||
|
child(13)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child(3)
|
||||||
|
child(4) {
|
||||||
|
child(7)
|
||||||
|
child(8)
|
||||||
|
child(9)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val expectedOrder = listOf(10, 5, 11, 12, 13, 6, 2, 3, 7, 8, 9, 4, 1)
|
||||||
|
assertContentEquals(expectedOrder, tree.toList().map { it.value })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun levelOrderIteratorTest() {
|
||||||
|
val tree = tree(1, TreeNodeIterators.LevelOrder) {
|
||||||
|
child(2) {
|
||||||
|
child(5) {
|
||||||
|
child(10)
|
||||||
|
}
|
||||||
|
child(6) {
|
||||||
|
child(11)
|
||||||
|
child(12)
|
||||||
|
child(13)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child(3)
|
||||||
|
child(4) {
|
||||||
|
child(7)
|
||||||
|
child(8)
|
||||||
|
child(9)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val expectedOrder = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
|
||||||
|
assertContentEquals(expectedOrder, tree.toList().map { it.value })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContentEquals
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertNull
|
||||||
|
|
||||||
|
class TreeNodeUtilitiesTest {
|
||||||
|
|
||||||
|
private val root = TreeNode(1)
|
||||||
|
private val a = TreeNode(2)
|
||||||
|
private val b = TreeNode(3)
|
||||||
|
|
||||||
|
init {
|
||||||
|
root.addChild(a)
|
||||||
|
a.addChild(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nodeCountCountsDescendantsExcludingRoot() {
|
||||||
|
assertEquals(0, TreeNode("solo").nodeCount())
|
||||||
|
assertEquals(2, root.nodeCount())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun heightIsLongestEdgePathToLeaf() {
|
||||||
|
assertEquals(0, TreeNode("solo").height())
|
||||||
|
assertEquals(2, root.height())
|
||||||
|
assertEquals(1, a.height())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun depthIsDistanceToRoot() {
|
||||||
|
assertEquals(0, root.depth())
|
||||||
|
assertEquals(1, a.depth())
|
||||||
|
assertEquals(2, b.depth())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun pathReturnsDescendantToReceiverChain() {
|
||||||
|
assertContentEquals(listOf(b, a, root), root.path(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun pathReturnsNullWhenNotADescendant() {
|
||||||
|
assertNull(root.path(TreeNode(99)))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun pathReturnsNullWhenDescendantIsRootItself() {
|
||||||
|
assertNull(root.path(root))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.exceptions.TreeNodeException
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContentEquals
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFailsWith
|
||||||
|
import kotlin.test.assertFalse
|
||||||
|
import kotlin.test.assertNull
|
||||||
|
import kotlin.test.assertSame
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class TreeNodeV4Test {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun addChildRejectsNodeThatAlreadyHasAParent() {
|
||||||
|
val a = TreeNode("a")
|
||||||
|
val b = TreeNode("b")
|
||||||
|
a.addChild(b)
|
||||||
|
|
||||||
|
val other = TreeNode("other")
|
||||||
|
assertFailsWith<TreeNodeException> { other.addChild(b) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun addChildRejectsCycles() {
|
||||||
|
val root = TreeNode("root")
|
||||||
|
val child = TreeNode("child")
|
||||||
|
root.addChild(child)
|
||||||
|
|
||||||
|
// Attaching an ancestor under its own descendant would create a cycle.
|
||||||
|
assertFailsWith<TreeNodeException> { child.addChild(root) }
|
||||||
|
// Attaching a node under itself is also a cycle.
|
||||||
|
assertFailsWith<TreeNodeException> { root.addChild(root) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun detachRemovesFromParent() {
|
||||||
|
val root = TreeNode("root")
|
||||||
|
val child = TreeNode("child")
|
||||||
|
root.addChild(child)
|
||||||
|
|
||||||
|
assertTrue(child.detach())
|
||||||
|
assertNull(child.parent)
|
||||||
|
assertContentEquals(emptyList(), root.children)
|
||||||
|
// Detached node can now be re-attached elsewhere.
|
||||||
|
val newParent = TreeNode("newParent")
|
||||||
|
newParent.addChild(child)
|
||||||
|
assertSame(newParent, child.parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun detachOnRootReturnsFalse() {
|
||||||
|
assertFalse(TreeNode("root").detach())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun removeChildOnlyRemovesDirectChildren() {
|
||||||
|
val root = TreeNode("root")
|
||||||
|
val parent = TreeNode("parent")
|
||||||
|
val grandchild = TreeNode("grandchild")
|
||||||
|
root.addChild(parent)
|
||||||
|
parent.addChild(grandchild)
|
||||||
|
|
||||||
|
// grandchild is not a direct child of root -> no-op, returns false.
|
||||||
|
assertFalse(root.removeChild(grandchild))
|
||||||
|
assertSame(parent, grandchild.parent)
|
||||||
|
|
||||||
|
// direct child removal works.
|
||||||
|
assertTrue(parent.removeChild(grandchild))
|
||||||
|
assertNull(grandchild.parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun clearOnNonRootKeepsItAttachedToItsParent() {
|
||||||
|
val root = TreeNode("root")
|
||||||
|
val branch = TreeNode("branch")
|
||||||
|
val leaf = TreeNode("leaf")
|
||||||
|
root.addChild(branch)
|
||||||
|
branch.addChild(leaf)
|
||||||
|
|
||||||
|
branch.clear()
|
||||||
|
|
||||||
|
assertContentEquals(emptyList(), branch.children)
|
||||||
|
assertSame(root, branch.parent) // branch stays attached to root
|
||||||
|
assertContentEquals(listOf(branch), root.children)
|
||||||
|
assertNull(leaf.parent) // former descendant is detached
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun iteratorAcceptsExplicitOrderWithoutMutatingDefault() {
|
||||||
|
val tree = tree(1) {
|
||||||
|
child(2) { child(4) }
|
||||||
|
child(3)
|
||||||
|
}
|
||||||
|
|
||||||
|
val postOrder = tree.iterator(TreeNodeIterators.PostOrder).asSequence().map { it.value }.toList()
|
||||||
|
assertContentEquals(listOf(4, 2, 3, 1), postOrder)
|
||||||
|
|
||||||
|
// Default order is unchanged (PreOrder).
|
||||||
|
assertEquals(TreeNodeIterators.PreOrder, tree.treeIterator)
|
||||||
|
assertContentEquals(listOf(1, 2, 4, 3), tree.map { it.value })
|
||||||
|
}
|
||||||
|
}
|
||||||
4
tree-structure-compose/api/tree-structure-compose.api
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
74
tree-structure-compose/build.gradle.kts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
|
alias(libs.plugins.composeMultiplatform)
|
||||||
|
alias(libs.plugins.composeCompiler)
|
||||||
|
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-compose", version.toString())
|
||||||
|
|
||||||
|
pom {
|
||||||
|
name.set("Tree Data Structure — Compose Multiplatform")
|
||||||
|
description.set("A LazyTree composable (expand/collapse, lazy rendering) 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()
|
||||||
|
google()
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
explicitApi()
|
||||||
|
jvmToolchain(21)
|
||||||
|
|
||||||
|
jvm()
|
||||||
|
|
||||||
|
@OptIn(ExperimentalWasmDsl::class)
|
||||||
|
wasmJs {
|
||||||
|
browser()
|
||||||
|
}
|
||||||
|
|
||||||
|
iosX64()
|
||||||
|
iosArm64()
|
||||||
|
iosSimulatorArm64()
|
||||||
|
|
||||||
|
sourceSets {
|
||||||
|
commonMain.dependencies {
|
||||||
|
api(project(":"))
|
||||||
|
implementation(compose.runtime)
|
||||||
|
implementation(compose.foundation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.compose
|
||||||
|
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.mutableStateMapOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import com.github.adriankuta.datastructure.tree.TreeNode
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A lazily-rendered, expand/collapse tree for Compose Multiplatform. Only the currently-visible
|
||||||
|
* nodes are composed, so it scales to large trees. Expansion state is remembered internally, keyed
|
||||||
|
* by node identity.
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
* LazyTree(root) { node, depth, expanded, toggle ->
|
||||||
|
* Row(Modifier.padding(start = (depth * 16).dp).clickable(onClick = toggle)) {
|
||||||
|
* if (!node.isLeaf) Text(if (expanded) "▾" else "▸")
|
||||||
|
* Text(node.value.toString())
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @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 nodeContent renders a single node. Receives the node, its depth (root = 0), whether it is
|
||||||
|
* expanded, and a `toggle` callback that flips this node's expansion state.
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
public fun <T> LazyTree(
|
||||||
|
root: TreeNode<T>,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
initiallyExpanded: Boolean = true,
|
||||||
|
nodeContent: @Composable (node: TreeNode<T>, depth: Int, expanded: Boolean, toggle: () -> Unit) -> Unit,
|
||||||
|
) {
|
||||||
|
val expansion = remember(root) { mutableStateMapOf<TreeNode<T>, Boolean>() }
|
||||||
|
val isExpanded: (TreeNode<T>) -> Boolean = { node -> expansion[node] ?: initiallyExpanded }
|
||||||
|
|
||||||
|
val visible = flattenVisible(root, isExpanded)
|
||||||
|
|
||||||
|
LazyColumn(modifier = modifier) {
|
||||||
|
items(visible.size) { index ->
|
||||||
|
val (node, depth) = visible[index]
|
||||||
|
nodeContent(node, depth, isExpanded(node)) {
|
||||||
|
expansion[node] = !isExpanded(node)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
private fun <T> flattenVisible(
|
||||||
|
root: TreeNode<T>,
|
||||||
|
isExpanded: (TreeNode<T>) -> Boolean,
|
||||||
|
): List<Pair<TreeNode<T>, Int>> {
|
||||||
|
val result = mutableListOf<Pair<TreeNode<T>, Int>>()
|
||||||
|
val stack = ArrayDeque<Pair<TreeNode<T>, Int>>()
|
||||||
|
stack.addLast(root to 0)
|
||||||
|
while (stack.isNotEmpty()) {
|
||||||
|
val (node, depth) = stack.removeLast()
|
||||||
|
result.add(node to depth)
|
||||||
|
if (isExpanded(node)) {
|
||||||
|
node.children.asReversed().forEach { child -> stack.addLast(child to depth + 1) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
public final class com/github/adriankuta/datastructure/tree/coroutines/TreeNodeFlowExtKt {
|
||||||
|
public static final fun asFlow (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;)Lkotlinx/coroutines/flow/Flow;
|
||||||
|
public static synthetic fun asFlow$default (Lcom/github/adriankuta/datastructure/tree/TreeNode;Lcom/github/adriankuta/datastructure/tree/iterators/TreeNodeIterators;ILjava/lang/Object;)Lkotlinx/coroutines/flow/Flow;
|
||||||
|
public static final fun levelOrderFlow (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lkotlinx/coroutines/flow/Flow;
|
||||||
|
public static final fun postOrderFlow (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lkotlinx/coroutines/flow/Flow;
|
||||||
|
public static final fun preOrderFlow (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lkotlinx/coroutines/flow/Flow;
|
||||||
|
}
|
||||||
|
|
||||||
89
tree-structure-coroutines/build.gradle.kts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
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-coroutines", version.toString())
|
||||||
|
|
||||||
|
pom {
|
||||||
|
name.set("Tree Data Structure — coroutines")
|
||||||
|
description.set("kotlinx.coroutines Flow traversal 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
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(":"))
|
||||||
|
api(libs.kotlinx.coroutines.core)
|
||||||
|
}
|
||||||
|
commonTest.dependencies {
|
||||||
|
implementation(kotlin("test"))
|
||||||
|
implementation(libs.kotlinx.coroutines.test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.coroutines
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.TreeNode
|
||||||
|
import com.github.adriankuta.datastructure.tree.asSequence
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.asFlow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emits this node and all of its descendants as a cold [Flow], traversed in the given [order].
|
||||||
|
* Useful for plugging tree traversal into coroutine/Flow pipelines (e.g. in a ViewModel).
|
||||||
|
*/
|
||||||
|
public fun <T> TreeNode<T>.asFlow(
|
||||||
|
order: TreeNodeIterators = TreeNodeIterators.PreOrder,
|
||||||
|
): Flow<TreeNode<T>> = asSequence(order).asFlow()
|
||||||
|
|
||||||
|
/** Pre-order traversal as a cold [Flow]. */
|
||||||
|
public fun <T> TreeNode<T>.preOrderFlow(): Flow<TreeNode<T>> = asFlow(TreeNodeIterators.PreOrder)
|
||||||
|
|
||||||
|
/** Post-order traversal as a cold [Flow]. */
|
||||||
|
public fun <T> TreeNode<T>.postOrderFlow(): Flow<TreeNode<T>> = asFlow(TreeNodeIterators.PostOrder)
|
||||||
|
|
||||||
|
/** Level-order (breadth-first) traversal as a cold [Flow]. */
|
||||||
|
public fun <T> TreeNode<T>.levelOrderFlow(): Flow<TreeNode<T>> = asFlow(TreeNodeIterators.LevelOrder)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.coroutines
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.iterators.TreeNodeIterators
|
||||||
|
import com.github.adriankuta.datastructure.tree.tree
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.toList
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class TreeNodeFlowTest {
|
||||||
|
|
||||||
|
private fun sample() = tree(1) {
|
||||||
|
child(2) {
|
||||||
|
child(4)
|
||||||
|
child(5)
|
||||||
|
}
|
||||||
|
child(3) {
|
||||||
|
child(6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun preOrderFlowEmitsInPreOrder() = runTest {
|
||||||
|
assertEquals(listOf(1, 2, 4, 5, 3, 6), sample().preOrderFlow().map { it.value }.toList())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun levelOrderFlowEmitsInLevelOrder() = runTest {
|
||||||
|
assertEquals(
|
||||||
|
listOf(1, 2, 3, 4, 5, 6),
|
||||||
|
sample().asFlow(TreeNodeIterators.LevelOrder).map { it.value }.toList(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
public final class com/github/adriankuta/datastructure/tree/serialization/TreeNodeDto {
|
||||||
|
public static final field Companion Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto$Companion;
|
||||||
|
public fun <init> (Ljava/lang/Object;Ljava/util/List;)V
|
||||||
|
public synthetic fun <init> (Ljava/lang/Object;Ljava/util/List;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
|
||||||
|
public final fun component1 ()Ljava/lang/Object;
|
||||||
|
public final fun component2 ()Ljava/util/List;
|
||||||
|
public final fun copy (Ljava/lang/Object;Ljava/util/List;)Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto;
|
||||||
|
public static synthetic fun copy$default (Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto;Ljava/lang/Object;Ljava/util/List;ILjava/lang/Object;)Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto;
|
||||||
|
public fun equals (Ljava/lang/Object;)Z
|
||||||
|
public final fun getChildren ()Ljava/util/List;
|
||||||
|
public final fun getValue ()Ljava/lang/Object;
|
||||||
|
public fun hashCode ()I
|
||||||
|
public fun toString ()Ljava/lang/String;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synthetic class com/github/adriankuta/datastructure/tree/serialization/TreeNodeDto$$serializer : kotlinx/serialization/internal/GeneratedSerializer {
|
||||||
|
public fun <init> (Lkotlinx/serialization/KSerializer;)V
|
||||||
|
public final fun childSerializers ()[Lkotlinx/serialization/KSerializer;
|
||||||
|
public final fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto;
|
||||||
|
public synthetic fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Ljava/lang/Object;
|
||||||
|
public final fun getDescriptor ()Lkotlinx/serialization/descriptors/SerialDescriptor;
|
||||||
|
public final fun serialize (Lkotlinx/serialization/encoding/Encoder;Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto;)V
|
||||||
|
public synthetic fun serialize (Lkotlinx/serialization/encoding/Encoder;Ljava/lang/Object;)V
|
||||||
|
public final fun typeParametersSerializers ()[Lkotlinx/serialization/KSerializer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final class com/github/adriankuta/datastructure/tree/serialization/TreeNodeDto$Companion {
|
||||||
|
public final fun serializer (Lkotlinx/serialization/KSerializer;)Lkotlinx/serialization/KSerializer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final class com/github/adriankuta/datastructure/tree/serialization/TreeNodeDtoKt {
|
||||||
|
public static final fun toDto (Lcom/github/adriankuta/datastructure/tree/TreeNode;)Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto;
|
||||||
|
public static final fun toTreeNode (Lcom/github/adriankuta/datastructure/tree/serialization/TreeNodeDto;)Lcom/github/adriankuta/datastructure/tree/TreeNode;
|
||||||
|
}
|
||||||
|
|
||||||
89
tree-structure-serialization/build.gradle.kts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
|
alias(libs.plugins.kotlinSerialization)
|
||||||
|
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-serialization", version.toString())
|
||||||
|
|
||||||
|
pom {
|
||||||
|
name.set("Tree Data Structure — kotlinx.serialization")
|
||||||
|
description.set("kotlinx.serialization support (TreeNodeDto round-trip) 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
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(":"))
|
||||||
|
api(libs.kotlinx.serialization.json)
|
||||||
|
}
|
||||||
|
commonTest.dependencies {
|
||||||
|
implementation(kotlin("test"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.serialization
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.TreeNode
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A serializable, acyclic view of a [TreeNode] subtree. [TreeNode] itself holds a back-reference to
|
||||||
|
* its parent (a cycle), so it cannot be `@Serializable` directly — convert to/from this DTO instead.
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
* val json = Json.encodeToString(tree.toDto())
|
||||||
|
* val restored = Json.decodeFromString<TreeNodeDto<String>>(json).toTreeNode()
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
public data class TreeNodeDto<T>(
|
||||||
|
public val value: T,
|
||||||
|
public val children: List<TreeNodeDto<T>> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Converts this subtree into a serializable [TreeNodeDto], preserving values and shape. */
|
||||||
|
public fun <T> TreeNode<T>.toDto(): TreeNodeDto<T> =
|
||||||
|
TreeNodeDto(value, children.map { it.toDto() })
|
||||||
|
|
||||||
|
/** Rebuilds a mutable [TreeNode] tree from this DTO. */
|
||||||
|
public fun <T> TreeNodeDto<T>.toTreeNode(): TreeNode<T> {
|
||||||
|
val node = TreeNode(value)
|
||||||
|
children.forEach { node.addChild(it.toTreeNode()) }
|
||||||
|
return node
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.github.adriankuta.datastructure.tree.serialization
|
||||||
|
|
||||||
|
import com.github.adriankuta.datastructure.tree.structurallyEquals
|
||||||
|
import com.github.adriankuta.datastructure.tree.tree
|
||||||
|
import kotlinx.serialization.encodeToString
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class TreeNodeSerializationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun roundTripsThroughJson() {
|
||||||
|
val original = tree("World") {
|
||||||
|
child("North America") { child("USA") }
|
||||||
|
child("Europe") {
|
||||||
|
child("Poland")
|
||||||
|
child("Germany")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val json = Json.encodeToString(original.toDto())
|
||||||
|
val restored = Json.decodeFromString<TreeNodeDto<String>>(json).toTreeNode()
|
||||||
|
|
||||||
|
assertTrue(original.structurallyEquals(restored))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun dtoMirrorsTreeShape() {
|
||||||
|
val dto = tree(1) {
|
||||||
|
child(2)
|
||||||
|
child(3) { child(4) }
|
||||||
|
}.toDto()
|
||||||
|
|
||||||
|
assertEquals(1, dto.value)
|
||||||
|
assertEquals(2, dto.children.size)
|
||||||
|
assertEquals(4, dto.children[1].children[0].value)
|
||||||
|
}
|
||||||
|
}
|
||||||
1
treedatastructure/.gitignore
vendored
@@ -1 +0,0 @@
|
|||||||
/build
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
apply plugin: 'com.android.library'
|
|
||||||
apply plugin: 'kotlin-android'
|
|
||||||
|
|
||||||
afterEvaluate {
|
|
||||||
generateReleaseBuildConfig.enabled = false
|
|
||||||
}
|
|
||||||
|
|
||||||
android {
|
|
||||||
compileSdkVersion 31
|
|
||||||
buildToolsVersion "31.0.0"
|
|
||||||
|
|
||||||
|
|
||||||
defaultConfig {
|
|
||||||
minSdkVersion 15
|
|
||||||
targetSdkVersion 31
|
|
||||||
versionName "2.0.2"
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
|
||||||
consumerProguardFiles 'consumer-rules.pro'
|
|
||||||
}
|
|
||||||
|
|
||||||
buildTypes {
|
|
||||||
release {
|
|
||||||
minifyEnabled false
|
|
||||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
|
|
||||||
implementation 'androidx.appcompat:appcompat:1.3.1'
|
|
||||||
implementation 'androidx.core:core-ktx:1.6.0'
|
|
||||||
testImplementation 'junit:junit:4.13.2'
|
|
||||||
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
|
|
||||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
|
|
||||||
}
|
|
||||||
|
|
||||||
ext {
|
|
||||||
PUBLISH_GROUP_ID = 'com.github.adriankuta'
|
|
||||||
PUBLISH_ARTIFACT_ID = 'tree-structure'
|
|
||||||
PUBLISH_VERSION = android.defaultConfig.versionName
|
|
||||||
}
|
|
||||||
|
|
||||||
apply from: "${rootProject.projectDir}/scripts/publish-module.gradle"
|
|
||||||
21
treedatastructure/proguard-rules.pro
vendored
@@ -1,21 +0,0 @@
|
|||||||
# Add project specific ProGuard rules here.
|
|
||||||
# You can control the set of applied configuration files using the
|
|
||||||
# proguardFiles setting in build.gradle.
|
|
||||||
#
|
|
||||||
# For more details, see
|
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
|
||||||
|
|
||||||
# If your project uses WebView with JS, uncomment the following
|
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
|
||||||
# class:
|
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
|
||||||
# public *;
|
|
||||||
#}
|
|
||||||
|
|
||||||
# Uncomment this to preserve the line number information for
|
|
||||||
# debugging stack traces.
|
|
||||||
#-keepattributes SourceFile,LineNumberTable
|
|
||||||
|
|
||||||
# If you keep the line number information, uncomment this to
|
|
||||||
# hide the original source file name.
|
|
||||||
#-renamesourcefileattribute SourceFile
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package com.github.adriankuta.datastructure.tree
|
|
||||||
|
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
|
|
||||||
import org.junit.Assert.*
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instrumented test, which will execute on an Android device.
|
|
||||||
*
|
|
||||||
* See [testing documentation](http://d.android.com/tools/testing).
|
|
||||||
*/
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
|
||||||
class ExampleInstrumentedTest {
|
|
||||||
@Test
|
|
||||||
fun useAppContext() {
|
|
||||||
// Context of the app under test.
|
|
||||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
|
||||||
assertEquals("com.github.adriankuta.datastructure.tree.test", appContext.packageName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
<manifest package="com.github.adriankuta.datastructure.tree" />
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
package com.github.adriankuta.datastructure.tree
|
|
||||||
|
|
||||||
open class TreeNode<T>(val value: T) : Iterable<TreeNode<T>>, ChildDeclarationInterface<T> {
|
|
||||||
|
|
||||||
private var _parent: TreeNode<T>? = null
|
|
||||||
/**
|
|
||||||
* The converse notion of a child, an immediate ancestor.
|
|
||||||
*/
|
|
||||||
val parent: TreeNode<T>?
|
|
||||||
get() = _parent
|
|
||||||
|
|
||||||
private val _children = mutableListOf<TreeNode<T>>()
|
|
||||||
/**
|
|
||||||
* A group of nodes with the same parent.
|
|
||||||
*/
|
|
||||||
val children: List<TreeNode<T>>
|
|
||||||
get() = _children
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add new child to current node or root.
|
|
||||||
*
|
|
||||||
* @param child A node which will be directly connected to current node.
|
|
||||||
*/
|
|
||||||
fun addChild(child: TreeNode<T>) {
|
|
||||||
child._parent = this
|
|
||||||
_children.add(child)
|
|
||||||
}
|
|
||||||
|
|
||||||
@JvmSynthetic
|
|
||||||
override fun child(value: T, childDeclaration: ChildDeclaration<T>?): TreeNode<T> {
|
|
||||||
val newChild = TreeNode(value)
|
|
||||||
if(childDeclaration != null)
|
|
||||||
newChild.childDeclaration()
|
|
||||||
_children.add(newChild)
|
|
||||||
return newChild
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes a single instance of the specified node from this tree, if it is present.
|
|
||||||
*
|
|
||||||
* @return `true` if the node has been successfully removed; `false` if it was not present in the tree.
|
|
||||||
*/
|
|
||||||
fun removeChild(child: TreeNode<T>): Boolean {
|
|
||||||
val removed = child._parent?._children?.remove(child)
|
|
||||||
child._parent = null
|
|
||||||
return removed ?: false
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This function go through tree and counts children. Root element is not counted.
|
|
||||||
* @return All child and nested child count.
|
|
||||||
*/
|
|
||||||
fun nodeCount(): Int {
|
|
||||||
if (_children.isEmpty())
|
|
||||||
return 0
|
|
||||||
return _children.size +
|
|
||||||
_children.sumOf { it.nodeCount() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return The number of edges on the longest path between current node and a descendant leaf.
|
|
||||||
*/
|
|
||||||
fun height(): Int {
|
|
||||||
val childrenMaxDepth = _children.map { it.height() }
|
|
||||||
.maxOrNull()
|
|
||||||
?: -1 // -1 because this method counts nodes, and edges are always one less then nodes.
|
|
||||||
return childrenMaxDepth + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Distance is the number of edges along the shortest path between two nodes.
|
|
||||||
* @return The distance between current node and the root.
|
|
||||||
*/
|
|
||||||
fun depth(): Int {
|
|
||||||
var depth = 0
|
|
||||||
var tempParent = parent
|
|
||||||
|
|
||||||
while (tempParent != null) {
|
|
||||||
depth++
|
|
||||||
tempParent = tempParent.parent
|
|
||||||
}
|
|
||||||
return depth
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove all children from root and every node in tree.
|
|
||||||
*/
|
|
||||||
fun clear() {
|
|
||||||
_parent = null
|
|
||||||
_children.forEach { it.clear() }
|
|
||||||
_children.clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun toString(): String {
|
|
||||||
return value.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun prettyString(): String {
|
|
||||||
val stringBuilder = StringBuilder()
|
|
||||||
print(stringBuilder, "", "")
|
|
||||||
return stringBuilder.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun print(stringBuilder: StringBuilder, prefix: String, childrenPrefix: String) {
|
|
||||||
stringBuilder.append(prefix)
|
|
||||||
stringBuilder.append(value)
|
|
||||||
stringBuilder.append('\n')
|
|
||||||
val childIterator = _children.iterator()
|
|
||||||
while (childIterator.hasNext()) {
|
|
||||||
val node = childIterator.next()
|
|
||||||
if (childIterator.hasNext()) {
|
|
||||||
node.print(stringBuilder, "$childrenPrefix├── ", "$childrenPrefix│ ")
|
|
||||||
} else {
|
|
||||||
node.print(stringBuilder, "$childrenPrefix└── ", "$childrenPrefix ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tree is iterated by using `Pre-order Traversal Algorithm"
|
|
||||||
* 1. Check if the current node is empty or null.
|
|
||||||
* 2. Display the data part of the root (or current node).
|
|
||||||
* 3. Traverse the left subtree by recursively calling the pre-order function.
|
|
||||||
* 4. Traverse the right subtree by recursively calling the pre-order function.
|
|
||||||
* ```
|
|
||||||
* E.g.
|
|
||||||
* 1
|
|
||||||
* / | \
|
|
||||||
* / | \
|
|
||||||
* 2 3 4
|
|
||||||
* / \ / | \
|
|
||||||
* 5 6 7 8 9
|
|
||||||
* / / | \
|
|
||||||
* 10 11 12 13
|
|
||||||
*
|
|
||||||
* Output: 1 2 5 10 6 11 12 13 3 4 7 8 9
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
override fun iterator(): Iterator<TreeNode<T>> = TreeNodeIterator(this)
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package com.github.adriankuta.datastructure.tree
|
|
||||||
|
|
||||||
typealias ChildDeclaration<T> = ChildDeclarationInterface<T>.() -> Unit
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This method can be used to initialize new tree.
|
|
||||||
* ```
|
|
||||||
* val root = tree("World") { ... }
|
|
||||||
* ```
|
|
||||||
* @param root Root element of new tree.
|
|
||||||
* @see [ChildDeclarationInterface.child]
|
|
||||||
*/
|
|
||||||
@JvmSynthetic
|
|
||||||
inline fun<reified T> tree(root: T, childDeclaration: ChildDeclaration<T>): TreeNode<T> {
|
|
||||||
val treeNode = TreeNode(root)
|
|
||||||
treeNode.childDeclaration()
|
|
||||||
return treeNode
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package com.github.adriankuta.datastructure.tree
|
|
||||||
|
|
||||||
import java.util.*
|
|
||||||
|
|
||||||
class TreeNodeIterator<T>(root: TreeNode<T>) : Iterator<TreeNode<T>> {
|
|
||||||
|
|
||||||
private val stack = Stack<TreeNode<T>>()
|
|
||||||
|
|
||||||
init {
|
|
||||||
stack.push(root)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun hasNext(): Boolean = !stack.empty()
|
|
||||||
|
|
||||||
override fun next(): TreeNode<T> {
|
|
||||||
val node = stack.pop()
|
|
||||||
node.children
|
|
||||||
.asReversed()
|
|
||||||
.forEach { stack.push(it) }
|
|
||||||
return node
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package com.github.adriankuta.datastructure.tree
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
import org.junit.Assert.*
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Example local unit test, which will execute on the development machine (host).
|
|
||||||
*
|
|
||||||
* See [testing documentation](http://d.android.com/tools/testing).
|
|
||||||
*/
|
|
||||||
class ExampleUnitTest {
|
|
||||||
@Test
|
|
||||||
fun addition_isCorrect() {
|
|
||||||
assertEquals(4, 2 + 2)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
package com.github.adriankuta.datastructure.tree
|
|
||||||
|
|
||||||
import org.hamcrest.CoreMatchers.`is`
|
|
||||||
import org.hamcrest.CoreMatchers.nullValue
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertThat
|
|
||||||
import org.junit.Test
|
|
||||||
|
|
||||||
class TreeNodeTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun removeNodeTest() {
|
|
||||||
val root = TreeNode("Root")
|
|
||||||
val beveragesNode = TreeNode("Beverages")
|
|
||||||
val curdNode = TreeNode("Curd")
|
|
||||||
root.addChild(beveragesNode)
|
|
||||||
root.addChild(curdNode)
|
|
||||||
|
|
||||||
val teaNode = TreeNode("tea")
|
|
||||||
val coffeeNode = TreeNode("coffee")
|
|
||||||
val milkShakeNode = TreeNode("Milk Shake")
|
|
||||||
beveragesNode.addChild(teaNode)
|
|
||||||
beveragesNode.addChild(coffeeNode)
|
|
||||||
beveragesNode.addChild(milkShakeNode)
|
|
||||||
|
|
||||||
val gingerTeaNode = TreeNode("ginger tea")
|
|
||||||
val normalTeaNode = TreeNode("normal tea")
|
|
||||||
teaNode.addChild(gingerTeaNode)
|
|
||||||
teaNode.addChild(normalTeaNode)
|
|
||||||
|
|
||||||
val yogurtNode = TreeNode("yogurt")
|
|
||||||
val lassiNode = TreeNode("lassi")
|
|
||||||
curdNode.addChild(yogurtNode)
|
|
||||||
curdNode.addChild(lassiNode)
|
|
||||||
|
|
||||||
assertEquals(
|
|
||||||
"Root\n" +
|
|
||||||
"├── Beverages\n" +
|
|
||||||
"│ ├── tea\n" +
|
|
||||||
"│ │ ├── ginger tea\n" +
|
|
||||||
"│ │ └── normal tea\n" +
|
|
||||||
"│ ├── coffee\n" +
|
|
||||||
"│ └── Milk Shake\n" +
|
|
||||||
"└── Curd\n" +
|
|
||||||
" ├── yogurt\n" +
|
|
||||||
" └── lassi\n", root.toString()
|
|
||||||
)
|
|
||||||
|
|
||||||
println("Remove: ${curdNode.value}")
|
|
||||||
root.removeChild(curdNode)
|
|
||||||
println("Remove: ${gingerTeaNode.value}")
|
|
||||||
root.removeChild(gingerTeaNode)
|
|
||||||
assertEquals(
|
|
||||||
"Root\n" +
|
|
||||||
"└── Beverages\n" +
|
|
||||||
" ├── tea\n" +
|
|
||||||
" │ └── normal tea\n" +
|
|
||||||
" ├── coffee\n" +
|
|
||||||
" └── Milk Shake\n", root.toString()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun clearTest() {
|
|
||||||
val root = TreeNode("Root")
|
|
||||||
val beveragesNode = TreeNode("Beverages")
|
|
||||||
val curdNode = TreeNode("Curd")
|
|
||||||
root.addChild(beveragesNode)
|
|
||||||
root.addChild(curdNode)
|
|
||||||
|
|
||||||
val teaNode = TreeNode("tea")
|
|
||||||
val coffeeNode = TreeNode("coffee")
|
|
||||||
val milkShakeNode = TreeNode("Milk Shake")
|
|
||||||
beveragesNode.addChild(teaNode)
|
|
||||||
beveragesNode.addChild(coffeeNode)
|
|
||||||
beveragesNode.addChild(milkShakeNode)
|
|
||||||
|
|
||||||
val gingerTeaNode = TreeNode("ginger tea")
|
|
||||||
val normalTeaNode = TreeNode("normal tea")
|
|
||||||
teaNode.addChild(gingerTeaNode)
|
|
||||||
teaNode.addChild(normalTeaNode)
|
|
||||||
|
|
||||||
val yogurtNode = TreeNode("yogurt")
|
|
||||||
val lassiNode = TreeNode("lassi")
|
|
||||||
curdNode.addChild(yogurtNode)
|
|
||||||
curdNode.addChild(lassiNode)
|
|
||||||
|
|
||||||
println(root.toString())
|
|
||||||
println(curdNode.height())
|
|
||||||
|
|
||||||
root.clear()
|
|
||||||
assertThat(root.children, `is`(emptyList()))
|
|
||||||
assertThat(beveragesNode.children, `is`(emptyList()))
|
|
||||||
assertThat(curdNode.children, `is`(emptyList()))
|
|
||||||
assertThat(teaNode.children, `is`(emptyList()))
|
|
||||||
assertThat(coffeeNode.children, `is`(emptyList()))
|
|
||||||
assertThat(milkShakeNode.children, `is`(emptyList()))
|
|
||||||
assertThat(gingerTeaNode.children, `is`(emptyList()))
|
|
||||||
assertThat(normalTeaNode.children, `is`(emptyList()))
|
|
||||||
assertThat(yogurtNode.children, `is`(emptyList()))
|
|
||||||
assertThat(lassiNode.children, `is`(emptyList()))
|
|
||||||
|
|
||||||
assertThat(root.parent, `is`(nullValue()))
|
|
||||||
assertThat(beveragesNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(curdNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(teaNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(coffeeNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(milkShakeNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(gingerTeaNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(normalTeaNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(yogurtNode.parent, `is`(nullValue()))
|
|
||||||
assertThat(lassiNode.parent, `is`(nullValue()))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun kotlinExtTest() {
|
|
||||||
val root = TreeNode("World")
|
|
||||||
val northA = TreeNode("North America")
|
|
||||||
val europe = TreeNode("Europe")
|
|
||||||
root.addChild(northA)
|
|
||||||
root.addChild(europe)
|
|
||||||
|
|
||||||
val usa = TreeNode("USA")
|
|
||||||
northA.addChild(usa)
|
|
||||||
|
|
||||||
val poland = TreeNode("Poland")
|
|
||||||
val france = TreeNode("France")
|
|
||||||
europe.addChild(poland)
|
|
||||||
europe.addChild(france)
|
|
||||||
|
|
||||||
val rootExt = tree("World") {
|
|
||||||
child("North America") {
|
|
||||||
child("USA")
|
|
||||||
}
|
|
||||||
child("Europe") {
|
|
||||||
child("Poland")
|
|
||||||
child("France")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assertEquals(root.prettyString(), rootExt.prettyString())
|
|
||||||
}
|
|
||||||
}
|
|
||||||