diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml new file mode 100644 index 0000000..7e7ccc2 --- /dev/null +++ b/.github/workflows/CI.yml @@ -0,0 +1,32 @@ +name: CI + +on: + push: + pull_request: + branches: [ "main" ] + +jobs: + Tests: + runs-on: ubuntu-latest + + steps: + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@417ae3ccd767c252f5661f1ace9f835f9654f2b5 + + - name: Build with Gradle Wrapper + run: ./gradlew build + + - name: Run autotests + run: ./gradlew test + + - name: Run Test Coverage + run: ./gradlew jacocoTestReport \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f7fffaa --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store +/lib/src/main/resources/ +/.idea/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d7b53d2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Ksenia Kotelnikova, Sofya Kozyreva, Sofia Shvorob + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +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 +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2fbf37e --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +## About the project + +This library allows you to use three types of binary search trees: simple, AVL and Red-Black tree. [AVL](https://en.wikipedia.org/wiki/AVL_tree) and [Red-Black](https://en.wikipedia.org/wiki/Red–black_tree) tree implement their natural balancing. + +## Getting started +1. Download our lib from [Releases](https://github.com/spbu-coding-2023/trees-5/releases) +2. Open your project +3. Go to `File > New > Module from Existing Sources...` +4. Choose the lib you downloaded +5. Add this in your program: + +``` + import trees.* + ``` +You can replace `*` with any specific tree + +## How to use +There are 4 public methods you can use for each tree: + +* `insert(key, value)` inserts a node with such key and value. If a node with the same key already exists in the tree, old value is replaced with the new one. Note that key should be of Comparable type. +* `delete(key)` deletes a node with such key. If there is no node with that key, nothing is done. +* `find(key)` finds a node with such key and returns its value. If there is no node with that key, null is returned. +* `preorderTraverse()` traverses the tree recursively from `parent` to `left child` to `right child` (specific for every tree) + +Now you can simply create a tree: `BSTree`, `AVLTree` or `RBTree`: +``` + val tree = RBTree() + ``` +Start inserting and deleting nodes: +``` + tree.insert(11, "Welcome to the jungle") + tree.insert(9, "We got fun and games") + tree.insert(27, "We take it day by day") + tree.delete(11) + val value1 = find(9) // value = "We got fun and games" + val value2 = find(15) // value = null + ``` +Here are some examples for traversing each tree: + +For `BSTree` it saves node's key: +``` + val bstree = BSTree() + bstree.insert(99, "Empty spaces") + bstree.insert(88, "What are we living for?") + bstree.insert(77, "Abandonded places") + val myList = bstree.preorderTraverse() // myList = [99, 88, 77] + ``` +For `AVLTree` it saves node's key and height: +``` + val avltree = AVLTree() + avltree.insert(11, "When you were here before") + avltree.insert(1, "Couldn't look you in the eye") + avltree.insert(111, "You're just like an angel") + val myList = avltree.preorderTraverse() // myList = [(11, 2), (1, 1), (111, 1)] + ``` +For `RBTree` it saves node's key and color: +``` + val rbtree = RBTree() + rbtree.insert(30, "...we built this house") + rbtree.insert(20, "On memories") + rbtree.insert(25, "Take my picture now") + val myList = rbtree.preorderTraverse() // myList = [(25, BLACK), (20, RED), (30, RED)] + ``` + +Have fun! +## Developers and contacts +* [p1onerka](https://github.com/p1onerka) (tg @p10nerka) +* [sofyak0zyreva](https://github.com/sofyak0zyreva) (tg @soffque) +* [shvorobsofia](https://github.com/shvorobsofia) (tg @fshv23) + +## License +The product is distributed under MIT license. Check LICENSE for more information diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..6907318 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Mar 23 16:46:44 MSK 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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 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/master/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 + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +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. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + 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. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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 Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +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. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/build.gradle b/lib/build.gradle new file mode 100644 index 0000000..534e573 --- /dev/null +++ b/lib/build.gradle @@ -0,0 +1,41 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' version '1.9.22' + id 'jacoco' +} + +group = 'org.example' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation("org.jetbrains.kotlin:kotlin-test") +} + +test { + useJUnitPlatform() + finalizedBy jacocoTestReport +} +kotlin { + jvmToolchain(15) +} + +jacocoTestReport { + dependsOn test +} + +jacoco { + toolVersion = "0.8.11" + reportsDirectory = layout.buildDirectory.dir('test_coverage') +} + +jacocoTestReport { + reports { + xml.required = false + csv.required = true + html.outputLocation = layout.buildDirectory.dir('jacocoHtml') + csv.outputLocation = layout.buildDirectory.file("jacoco/report.csv") + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/nodes/AVLNode.kt b/lib/src/main/kotlin/nodes/AVLNode.kt new file mode 100644 index 0000000..6c50a57 --- /dev/null +++ b/lib/src/main/kotlin/nodes/AVLNode.kt @@ -0,0 +1,5 @@ +package nodes + +class AVLNode, V>(key: K, value: V): AbstractNode>(key, value) { + var height = 1 +} \ No newline at end of file diff --git a/lib/src/main/kotlin/nodes/AbstractNode.kt b/lib/src/main/kotlin/nodes/AbstractNode.kt new file mode 100644 index 0000000..2795f1a --- /dev/null +++ b/lib/src/main/kotlin/nodes/AbstractNode.kt @@ -0,0 +1,6 @@ +package nodes + +abstract class AbstractNode, V, someNode : AbstractNode>(val key:K, var value: V) { + var leftChild: someNode? = null + var rightChild: someNode? = null +} \ No newline at end of file diff --git a/lib/src/main/kotlin/nodes/BSNode.kt b/lib/src/main/kotlin/nodes/BSNode.kt new file mode 100644 index 0000000..c642892 --- /dev/null +++ b/lib/src/main/kotlin/nodes/BSNode.kt @@ -0,0 +1,3 @@ +package nodes + +class BSNode, V>(key: K, value: V) : AbstractNode>(key, value) \ No newline at end of file diff --git a/lib/src/main/kotlin/nodes/RBNode.kt b/lib/src/main/kotlin/nodes/RBNode.kt new file mode 100644 index 0000000..1f4992d --- /dev/null +++ b/lib/src/main/kotlin/nodes/RBNode.kt @@ -0,0 +1,9 @@ +package nodes + +enum class Color { + RED, BLACK +} + +class RBNode, V>(key: K, value: V): AbstractNode>(key, value) { + var color: Color = Color.RED +} \ No newline at end of file diff --git a/lib/src/main/kotlin/trees/AVLTree.kt b/lib/src/main/kotlin/trees/AVLTree.kt new file mode 100644 index 0000000..a5173f9 --- /dev/null +++ b/lib/src/main/kotlin/trees/AVLTree.kt @@ -0,0 +1,94 @@ +package trees + +import nodes.AVLNode +import kotlin.math.max + +class AVLTree, V> : BalancedTree>() { + override fun createNewNode(key: K, value: V) = AVLNode(key, value) + + override fun insert(key: K, value: V) { + val insertedNode = insertNode(key, value) + if (insertedNode != null) { + findParent(insertedNode)?.let { balance(it) } + } + } + + override fun delete(key: K) { + val nodeToDelete = findNodeByKey(key) + if (nodeToDelete != null) { + val deletedNodeParent = findParent(nodeToDelete) + val childrenNum = getNumberOfChildren(nodeToDelete) + val newNode = deleteNode(key) + /* deleting a leaf */ + if (newNode == null) { + deletedNodeParent?.let { balance(it) } + } + else if (childrenNum == 1) { + balance(newNode) + } + /* deleting a node with 2 children */ + else { + val newNodeParent = findMinNodeInRight(newNode.rightChild) + if (newNodeParent != null) balance(newNodeParent) + else balance(newNode) + } + } + } + + private fun getNumberOfChildren(node: AVLNode): Int { + return when { + node.leftChild != null && node.rightChild != null -> 2 + node.leftChild != null || node.rightChild != null -> 1 + else -> 0 + } + } + + private fun getHeight(node: AVLNode?): Int { + return node?.height ?: 0 + } + + private fun updateHeight(node: AVLNode) { + node.height = max(getHeight(node.rightChild), getHeight(node.leftChild)) + 1 + } + + private fun getBalanceFactor(node: AVLNode): Int { + return getHeight(node.rightChild) - getHeight(node.leftChild) + } + + /* balances a tree by performing left & right rotations + if absolute value of balance factor is more than 1 */ + override fun balance(curNode: AVLNode, isAfterInsert: Boolean) { + when (getBalanceFactor(curNode)) { + -2 -> { + curNode.leftChild?.let { if (getBalanceFactor(it) == 1) rotateLeft(it, findParent(it)) } + rotateRight(curNode, findParent(curNode)) + } + + 2 -> { + curNode.rightChild?.let { if (getBalanceFactor(it) == -1) rotateRight(it, findParent(it)) } + rotateLeft(curNode, findParent(curNode)) + } + + else -> updateHeight(curNode) + } + findParent(curNode)?.let { balance(it) } + } + + override fun rotateRight(node: AVLNode, parentNode: AVLNode?) { + super.rotateRight(node, parentNode) + updateHeight(node) + } + + override fun rotateLeft(node: AVLNode, parentNode: AVLNode?) { + super.rotateLeft(node, parentNode) + updateHeight(node) + } + + fun preorderTraverse(): List> { + val listOfNodes = mutableListOf>() + traverse(root, listOfNodes) + val listOfKeysAndHeights = mutableListOf>() + listOfNodes.forEach { listOfKeysAndHeights.add(Pair(it.key, it.height)) } + return listOfKeysAndHeights + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/trees/AbstractTree.kt b/lib/src/main/kotlin/trees/AbstractTree.kt new file mode 100644 index 0000000..1e4ab10 --- /dev/null +++ b/lib/src/main/kotlin/trees/AbstractTree.kt @@ -0,0 +1,154 @@ +package trees + +import nodes.AbstractNode + +abstract class AbstractTree, V, someNode : AbstractNode> { + protected var root: someNode? = null + + protected abstract fun createNewNode(key: K, value: V): someNode + + open fun insert(key: K, value: V) { + insertNode(key, value) + } + + protected fun insertNode(key: K, value: V): someNode? { + val nodeToInsert = createNewNode(key, value) + var curNode = root + + if (curNode == null) { + root = nodeToInsert + return root + } + + while ((curNode != null) && (curNode != nodeToInsert)) { + when { + (curNode.key == nodeToInsert.key) -> { + curNode.value = nodeToInsert.value + break + } + + ((curNode.leftChild == null) && (nodeToInsert.key < curNode.key)) -> { + curNode.leftChild = nodeToInsert + curNode = curNode.leftChild + } + + ((curNode.rightChild == null) && (nodeToInsert.key > curNode.key)) -> { + curNode.rightChild = nodeToInsert + curNode = curNode.rightChild + } + + nodeToInsert.key < curNode.key -> { + curNode = curNode.leftChild + } + + nodeToInsert.key > curNode.key -> { + curNode = curNode.rightChild + } + } + } + return curNode + + } + + open fun delete(key: K) { + deleteNode(key) + } + + protected fun deleteNode(key: K): someNode? { + val nodeToDelete = findNodeByKey(key) + if ((nodeToDelete == null) || (root == null)) return null + val parentNode = findParent(nodeToDelete) + if ((nodeToDelete != root) && (parentNode == null)) { + throw IllegalArgumentException("Non-root node should have parent") + } + when { + /* node has no children */ + (nodeToDelete.leftChild == null && nodeToDelete.rightChild == null) -> { + changeChild(nodeToDelete, parentNode, null) + return null + } + + /* node has 1 child */ + (nodeToDelete.leftChild == null || nodeToDelete.rightChild == null) -> { + if (nodeToDelete.leftChild == null) { + changeChild(nodeToDelete, parentNode, nodeToDelete.rightChild) + return nodeToDelete.rightChild + } else { + changeChild(nodeToDelete, parentNode, nodeToDelete.leftChild) + return nodeToDelete.leftChild + } + } + + /* node has 2 children */ + else -> { + val replacementNode = findMinNodeInRight(nodeToDelete.rightChild) + ?: throw IllegalArgumentException ("Node with 2 children must have a right child") + changeChild(replacementNode, findParent(replacementNode), replacementNode.rightChild) + replacementNode.leftChild = nodeToDelete.leftChild + replacementNode.rightChild = nodeToDelete.rightChild + changeChild(nodeToDelete, parentNode, replacementNode) + return replacementNode + } + } + } + + protected fun findParent(node: someNode): someNode? { + var curNode = root + while (curNode != null) { + if (curNode.key == node.key) return null + if (curNode.leftChild?.key == node.key || curNode.rightChild?.key == node.key) return curNode + curNode = if (curNode.key < node.key) curNode.rightChild else curNode.leftChild + } + return null + } + + /** rebinds "children" link of a ParentNode from one node to another + * + * parentNode --> parentNode + * / / + * node replacementNode + */ + protected fun changeChild(node: someNode, parentNode: someNode?, replacementNode: someNode?) { + if (parentNode == null) { + if (root == node) root = replacementNode + } + else { + if (parentNode.rightChild == node) parentNode.rightChild = replacementNode + else if (parentNode.leftChild == node) parentNode.leftChild = replacementNode + } + } + + /* finds node with the minimum key in given right subtree*/ + protected fun findMinNodeInRight(rightSubtree: someNode?): someNode? { + var minNode = rightSubtree + while (true) { + minNode = minNode?.leftChild ?: break + } + if (minNode != null) return minNode + return null + } + + fun find(key: K): V? { + return findNodeByKey(key)?.value + } + + protected fun findNodeByKey(key: K): someNode? { + var curNode: someNode? = root ?: return null + while (curNode != null) { + curNode = when { + (curNode.key == key) -> return curNode + (curNode.key > key) -> curNode.leftChild + else -> curNode.rightChild + } + } + return null + } + + protected fun traverse(curNode: someNode?, listOfNodes: MutableList) { + if (curNode != null) { + listOfNodes.add(curNode) + traverse(curNode.leftChild, listOfNodes) + traverse(curNode.rightChild, listOfNodes) + } + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/trees/BSTree.kt b/lib/src/main/kotlin/trees/BSTree.kt new file mode 100644 index 0000000..a894359 --- /dev/null +++ b/lib/src/main/kotlin/trees/BSTree.kt @@ -0,0 +1,15 @@ +package trees + +import nodes.BSNode + +class BSTree, V> : AbstractTree>() { + override fun createNewNode(key: K, value: V): BSNode = BSNode(key, value) + + fun preorderTraverse(): List { + val listOfNodes = mutableListOf>() + traverse(root, listOfNodes) + val listOfKeys = mutableListOf() + listOfNodes.forEach { listOfKeys.add(it.key) } + return listOfKeys + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/trees/BalancedTree.kt b/lib/src/main/kotlin/trees/BalancedTree.kt new file mode 100644 index 0000000..489c887 --- /dev/null +++ b/lib/src/main/kotlin/trees/BalancedTree.kt @@ -0,0 +1,21 @@ +package trees + +import nodes.AbstractNode + +abstract class BalancedTree, V, someNode: AbstractNode> : AbstractTree() { + protected abstract fun balance(curNode: someNode, isAfterInsert: Boolean = true) + + protected open fun rotateRight(node: someNode, parentNode: someNode?) { + val tempNode = node.leftChild ?: throw IllegalArgumentException("Node must have left child for right rotation") + node.leftChild = tempNode.rightChild + tempNode.rightChild = node + changeChild(node, parentNode, tempNode) + } + + protected open fun rotateLeft(node: someNode, parentNode: someNode?) { + val tempNode = node.rightChild ?: throw IllegalArgumentException("Node must have right child for left rotation") + node.rightChild = tempNode.leftChild + tempNode.leftChild = node + changeChild(node, parentNode,tempNode) + } +} \ No newline at end of file diff --git a/lib/src/main/kotlin/trees/RBTree.kt b/lib/src/main/kotlin/trees/RBTree.kt new file mode 100644 index 0000000..1aaf699 --- /dev/null +++ b/lib/src/main/kotlin/trees/RBTree.kt @@ -0,0 +1,264 @@ +package trees + +import nodes.Color +import nodes.RBNode + +class RBTree, V> : BalancedTree>() { + private fun getGrandparent(node: RBNode): RBNode? { + val parent = findParent(node) ?: return null + val grandparent = findParent(parent) + return grandparent + } + + private fun getSibling(node: RBNode): RBNode? { + val parent = findParent(node) ?: return null + return if (node == parent.leftChild) { + parent.rightChild + } else { + parent.leftChild + } + } + + private fun getUncle(node: RBNode): RBNode? { + val parent = findParent(node) ?: return null + val grandparent = findParent(parent) + return if (parent == grandparent?.leftChild) { + grandparent.rightChild + } else { + grandparent?.leftChild + } + } + + override fun insert(key: K, value: V) { + val insertedNode = insertNode(key, value) ?: throw IllegalArgumentException("Nothing to insert") + balance(insertedNode, true) + } + + override fun createNewNode(key: K, value: V): RBNode = RBNode(key, value) + + override fun balance(curNode: RBNode, isAfterInsert: Boolean) { + if (isAfterInsert) { + balanceAfterInsert(curNode) + } else { + balanceAfterDelete(curNode) + } + } + + private fun balanceAfterInsert(curNode: RBNode) { + var insertedNode = curNode + insertedNode.color = Color.RED + + /* case 1: insertedNode is root */ + if (root == insertedNode) { + insertedNode.color = Color.BLACK + return + } + + var parent = findParent(insertedNode) ?: throw IllegalArgumentException("Non-root should have parent") + + /* case 2: parent of insertedNode is black */ + if (parent.color == Color.BLACK) { + return + } + + val uncle = getUncle(insertedNode) + val grandparent = getGrandparent(insertedNode) + ?: throw IllegalArgumentException("Every node by that point should have grandparent") + + /* case 3: uncle is non-null and red (so both uncle and parent are red) */ + if ((uncle != null) && (uncle.color == Color.RED)) { + parent.color = Color.BLACK + uncle.color = Color.BLACK + grandparent.color = Color.RED + balanceAfterInsert(grandparent) + return + } + + /* case 4: uncle is black; grandparent, parent and node form a "triangle" + * G G + * / \ + * P - left triangle P - right triangle + * \ / + * N N + * + */ + if ((insertedNode == parent.rightChild) && (parent == grandparent.leftChild)) { + rotateLeft(parent, grandparent) + parent = insertedNode + insertedNode = + insertedNode.leftChild ?: throw IllegalArgumentException("Node should have child after left rotation") + } else if ((insertedNode == parent.leftChild) && (parent == grandparent.rightChild)) { + rotateRight(parent, grandparent) + parent = insertedNode + insertedNode = insertedNode.rightChild + ?: throw IllegalArgumentException("Node should have right child after right rotation") + } + + /* case 5: grandparent, parent and node form a "line" + * + * G G + * / \ + * P - left line P - right line + * / \ + * N N + * + */ + parent.color = Color.BLACK + grandparent.color = Color.RED + if ((insertedNode == parent.leftChild) && (parent == grandparent.leftChild)) { + rotateRight(grandparent, findParent(grandparent)) + } else { + rotateLeft(grandparent, findParent(grandparent)) + } + return + } + + override fun delete(key: K) { + val nodeToDelete = findNodeByKey(key) ?: return + val child: RBNode? + when { + nodeToDelete.rightChild != null && nodeToDelete.leftChild != null -> { + child = findMinNodeInRight(nodeToDelete.rightChild) + ?: throw IllegalArgumentException("Node must have right child") + val newNode = child + delete(child.key) + newNode.color = nodeToDelete.color + newNode.leftChild = nodeToDelete.leftChild + newNode.rightChild = nodeToDelete.rightChild + changeChild(nodeToDelete, findParent(nodeToDelete), newNode) + return + } + + nodeToDelete.rightChild != null -> child = nodeToDelete.rightChild + nodeToDelete.leftChild != null -> child = nodeToDelete.leftChild + else -> { + child = null + if (nodeToDelete.color != Color.RED) balance(nodeToDelete, false) + } + } + when { + (nodeToDelete.color == Color.RED) -> { + deleteNode(nodeToDelete.key) + return + } + + (nodeToDelete.color == Color.BLACK && child?.color == Color.RED) -> { + deleteNode(nodeToDelete.key) + child.color = Color.BLACK + return + } + + else -> { + deleteNode(nodeToDelete.key) + if (child != null) balance(nodeToDelete, false) + } + } + } + + private fun balanceAfterDelete(node: RBNode) { + /* case 1: child of nodeToDelete is new root */ + var parent = findParent(node) ?: return + var sibling = getSibling(node) + + /** case 2: sibling of child is red + * BLACK + * / \ + * child RED + */ + if (sibling?.color == Color.RED) { + parent.color = Color.RED + sibling.color = Color.BLACK + if (node == parent.leftChild) { + val grandparent = getGrandparent(node) + rotateLeft(parent, grandparent) + } else { + val grandparent = getGrandparent(node) + rotateRight(parent, grandparent) + } + } + + /** case 3: parent, sibling and its children are black + * BLACK + * / \ + * child BLACK + * / \ + * BLACK BLACK + */ + sibling = getSibling(node) + parent = findParent(node) ?: throw IllegalArgumentException("Parent cannot be null") + if (parent.color == Color.BLACK && (sibling?.color == Color.BLACK) && + (sibling.rightChild?.color == Color.BLACK || sibling.rightChild == null) + && (sibling.leftChild?.color == Color.BLACK || sibling.leftChild == null) + ) { + sibling.color = Color.RED + balanceAfterDelete(parent) + } + + /** case 4: parent is red, sibling and its children are black + * RED + * / \ + * child BLACK + * / \ + * BLACK BLACK + */ + else if (parent.color == Color.RED && sibling?.color == Color.BLACK && + (sibling.rightChild?.color == Color.BLACK || sibling.rightChild == null) + && (sibling.leftChild?.color == Color.BLACK || sibling.leftChild == null) + ) { + sibling.color = Color.RED + parent.color = Color.BLACK + } + + /** case 5: sibling is black & leftChild, its leftChild is red and its rightChild is black + * parent + * / \ + * BLACK child + * / \ + * RED BLACK + */ + else { + if (node == parent.leftChild && sibling?.color == Color.BLACK && + (sibling.rightChild?.color == Color.BLACK || sibling.rightChild == null) && sibling.leftChild?.color == Color.RED + ) { + sibling.color = Color.RED + sibling.leftChild?.color = Color.BLACK + rotateRight(sibling, parent) + } else if (node == parent.rightChild && sibling?.color == Color.BLACK && + sibling.rightChild?.color == Color.RED && (sibling.leftChild?.color == Color.BLACK || sibling.leftChild == null) + ) { + sibling.color = Color.RED + sibling.rightChild?.color = Color.BLACK + rotateLeft(sibling, parent) + } + + /** case 6: sibling is right(left)Child and is black, its right(left)Child is red + * parent or parent + * / \ / \ + * child BLACK BLACK child + * \ / + * RED RED + */ + sibling = getSibling(node) ?: throw IllegalArgumentException("Sibling cannot be null") + parent = findParent(node) ?: throw IllegalArgumentException("Parent cannot be null") + val grandparent = getGrandparent(node) + val color = parent.color + sibling.color = color + parent.color = Color.BLACK + if (node == parent.leftChild) { + sibling.rightChild?.color = Color.BLACK + rotateLeft(parent, grandparent) + } else { + sibling.leftChild?.color = Color.BLACK + rotateRight(parent, grandparent) + } + } + } + + fun preorderTraverse(): List> { + val listOfNodes = mutableListOf>() + traverse(root, listOfNodes) + val listOfKeysAndColors = mutableListOf>() + listOfNodes.forEach { listOfKeysAndColors.add(Pair(it.key, it.color)) } + return listOfKeysAndColors + } +} \ No newline at end of file diff --git a/lib/src/test/kotlin/treesTests/AVLTreeTest.kt b/lib/src/test/kotlin/treesTests/AVLTreeTest.kt new file mode 100644 index 0000000..79724d9 --- /dev/null +++ b/lib/src/test/kotlin/treesTests/AVLTreeTest.kt @@ -0,0 +1,150 @@ +package treesTests + +import trees.AVLTree +import nodes.AVLNode +import org.junit.jupiter.api.Assertions.assertEquals +import kotlin.test.Test + +class AVLTreeTest : AbstractTest, AVLTree>() { + + override fun createNewTree(): AVLTree = AVLTree() + + @Test + fun `traverse AVL tree`() { + val expectedKeysAndHeights = listOf(Pair(444, 3), Pair(222, 2), Pair(111, 1), Pair(333, 1), Pair(666, 2), Pair(555, 1), Pair(777, 1)) + val actualKeysAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + override fun `insert root in empty tree`() { + super.`insert root in empty tree`() + val expectedKeysAndHeights = listOf(Pair(100, 1)) + val actualKeysAndHeights = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + override fun `delete root from one-node tree`() { + super.`delete root from one-node tree`() + val expectedKeysAndHeights: List> = listOf() + val actualKeysAndHeights = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + override fun `insert node with existing key`() { + super.`insert node with existing key`() + val expectedKeysAndHeights = listOf(Pair(444, 3), Pair(222, 2), Pair(111, 1), Pair(333, 1), Pair(666, 2), Pair(555, 1), Pair(777, 1)) + val actualKeysAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + override fun `delete node with non-existing key`() { + super.`delete node with non-existing key`() + val expectedKeysAndHeights = listOf(Pair(444, 3), Pair(222, 2), Pair(111, 1), Pair(333, 1), Pair(666, 2), Pair(555, 1), Pair(777, 1)) + val actualKeysAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + override fun `delete node from empty tree`() { + super.`delete node from empty tree`() + val expectedKeysAndHeightsAndHeights: List> = listOf() + val actualKeysAndHeightsAndHeights = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndHeightsAndHeights, actualKeysAndHeightsAndHeights) + } + + @Test + fun `insert node and perform left rotation`() { //I THINK it is left rotation + super.`simple insert test`() + bigTree.insert(1111, "hi there") + bigTree.insert(2222, "hi hi") + val expectedKeysAndHeights = listOf(Pair(444, 4), Pair(222, 2), Pair(111, 1), Pair(333, 1), Pair(666, 3), Pair(555, 1), Pair(1111, 2), Pair(777, 1), Pair(2222, 1)) + val actualKeysAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + fun `insert node and perform right rotation`() { //I THINK it is left rotation + bigTree.insert(55, "oh no") + bigTree.insert(22, "here we go again") + val expectedKeysAndHeights = listOf(Pair(444, 4), Pair(222, 3), Pair(55, 2), Pair(22, 1), Pair(111, 1), Pair(333, 1), Pair(666, 2), Pair(555, 1), Pair(777, 1)) + val actualKeysAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + fun `insert node and perform left-right rotation`() { + bigTree.insert(676, "oh no") + bigTree.insert(677, "hi") + val expectedKeysAndHeights = listOf(Pair(444, 4), Pair(222, 2), Pair(111, 1), Pair(333, 1), Pair(666, 3), Pair(555, 1), Pair(677, 2), Pair(676, 1), Pair(777, 1)) + val actualKeysAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + fun `insert node and perform right-left rotation`() { + bigTree.insert(344, "oh no") + bigTree.insert(345, "hi") + val expectedKeysAndHeights = listOf(Pair(444, 4), Pair(222, 3), Pair(111, 1), Pair(344, 2), Pair(333, 1), Pair(345, 1), Pair(666, 2), Pair(555, 1), Pair(777, 1)) + val actualKeysAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeights, actualKeysAndHeights) + } + + @Test + fun `delete node with no children and perform left rotation`() { + bigTree.delete(111) + val expectedKeysAndHeightsAndHeights = listOf(Pair(444, 3), Pair(222, 2), Pair(333, 1), Pair(666, 2), Pair(555, 1), Pair(777, 1)) + val actualKeysAndHeightsAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeightsAndHeights, actualKeysAndHeightsAndHeights) + } + + @Test + fun `delete node with no children and perform right-left rotation`() { + bigTree.delete(333) + bigTree.insert(1111, "hi") + bigTree.delete(555) + val expectedKeysAndHeightsAndHeights = listOf(Pair(444, 3), Pair(222, 2), Pair(111, 1), Pair(777, 2), Pair(666, 1), Pair(1111, 1)) + val actualKeysAndHeightsAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeightsAndHeights, actualKeysAndHeightsAndHeights) + } + + @Test + fun `delete node with one child and perform rotations`() { + bigTree.delete(111) + bigTree.insert(676, "end") + bigTree.delete(222) + val expectedKeysAndHeightsAndHeights = listOf(Pair(666, 3), Pair(444, 2), Pair(333, 1), Pair(555, 1), Pair(777, 2), Pair(676, 1)) + val actualKeysAndHeightsAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeightsAndHeights, actualKeysAndHeightsAndHeights) + } + + @Test + fun `delete node with two children and perform right-left rotation`() { + bigTree.insert(676, "end") + bigTree.delete(555) + val expectedKeysAndHeightsAndHeights = listOf(Pair(444, 3), Pair(222, 2), Pair(111, 1), Pair(333, 1), Pair(676, 2), Pair(666, 1), Pair(777, 1)) + val actualKeysAndHeightsAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeightsAndHeights, actualKeysAndHeightsAndHeights) + } + + @Test + fun `delete node with two children and perform left-right rotations`() { + bigTree.delete(666) + bigTree.delete(777) + bigTree.delete(222) + val expectedKeysAndHeightsAndHeights = listOf(Pair(444, 3), Pair(333, 2), Pair(111, 1), Pair(555, 1)) + val actualKeysAndHeightsAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeightsAndHeights, actualKeysAndHeightsAndHeights) + } + + @Test + fun `delete root with two children`() { + bigTree.delete(444) + val expectedKeysAndHeightsAndHeights = listOf(Pair(555, 3), Pair(222, 2), Pair(111, 1), Pair(333, 1), Pair(666, 2), Pair(777, 1)) + val actualKeysAndHeightsAndHeights = bigTree.preorderTraverse() + assertEquals(expectedKeysAndHeightsAndHeights, actualKeysAndHeightsAndHeights) + } +} diff --git a/lib/src/test/kotlin/treesTests/AbstractTest.kt b/lib/src/test/kotlin/treesTests/AbstractTest.kt new file mode 100644 index 0000000..0645f24 --- /dev/null +++ b/lib/src/test/kotlin/treesTests/AbstractTest.kt @@ -0,0 +1,77 @@ +package treesTests + +import trees.AbstractTree +import nodes.AbstractNode +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.BeforeEach +import kotlin.test.Test + +abstract class AbstractTest, V, someNode : AbstractNode, someTree : AbstractTree> { + protected abstract fun createNewTree(): someTree + protected lateinit var bigTree: someTree + protected lateinit var emptyTree: someTree + + @BeforeEach + fun setup() { + bigTree = createNewTree() + bigTree.insert(444, "first kitten") + bigTree.insert(222, "second kitten") + bigTree.insert(555, "third kitten") + bigTree.insert(111, "fourth kitten") + bigTree.insert(333, "fifth kitten") + bigTree.insert(666,"sixth kitten") + bigTree.insert(777, "last kitten") + } + + @Test + /* this case is equal to all trees, so it is final */ + fun `find node by key`() { + val expectedValue = "second kitten" + val actuallyValue = bigTree.find(222) + assertEquals(expectedValue, actuallyValue) + } + + open fun `insert root in empty tree`() { + emptyTree = createNewTree() + emptyTree.insert(100, "say hi to the root!") + } + + open fun `delete root from one-node tree`() { + emptyTree = createNewTree() + emptyTree.insert(100, "hm.. looks like its gone") + emptyTree.delete(100) + } + + open fun `simple insert test`() { } + + open fun `insert node with existing key`() { + bigTree.insert(777, "oh u came here twice sweetie") + } + + open fun `delete node with non-existing key`() { + bigTree.delete(1) + } + + open fun `delete node from empty tree`() { + emptyTree = createNewTree() + emptyTree.delete(5) + } + + open fun `delete node with no children`() { + bigTree.delete(777) + } + + open fun `delete node with one right child`() { + bigTree.insert(1000, "last one i swear") + bigTree.delete(777) + } + + open fun `delete node with one left child`() { + bigTree.insert(676, "now im sure") + bigTree.delete(777) + } + + open fun `delete node with two children`() { + bigTree.delete(555) + } +} diff --git a/lib/src/test/kotlin/treesTests/BSTreeTest.kt b/lib/src/test/kotlin/treesTests/BSTreeTest.kt new file mode 100644 index 0000000..2499007 --- /dev/null +++ b/lib/src/test/kotlin/treesTests/BSTreeTest.kt @@ -0,0 +1,99 @@ +package treesTests + +import trees.BSTree +import nodes.BSNode +import org.junit.jupiter.api.Assertions.assertEquals +import kotlin.test.Test + +class BSTreeTest : AbstractTest, BSTree>() { + + override fun createNewTree(): BSTree = BSTree() + + @Test + fun `traverse bst tree`() { + val expectedKeys: List = listOf(444, 222, 111, 333, 555, 666, 777) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `insert root in empty tree`() { + super.`insert root in empty tree`() + val expectedKeys = listOf(100) + val actualKeys = emptyTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `delete root from one-node tree`() { + super.`delete root from one-node tree`() + val expectedKeys: List = listOf() + val actualKeys = emptyTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `simple insert test`() { + super.`simple insert test`() + bigTree.insert(1111, "oh another kitten") + val expectedKeys = listOf(444, 222, 111, 333, 555, 666, 777, 1111) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `insert node with existing key`() { + super.`insert node with existing key`() + val expectedKeys = listOf(444, 222, 111, 333, 555, 666, 777) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `delete node with non-existing key`() { + super.`delete node with non-existing key`() + val expectedKeys = listOf(444, 222, 111, 333, 555, 666, 777) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `delete node from empty tree`() { + super.`delete node from empty tree`() + val expectedKeys: List = listOf() + val actualKeys = emptyTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `delete node with no children`() { + super.`delete node with no children`() + val expectedKeys = listOf(444, 222, 111, 333, 555, 666) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `delete node with one right child`() { + super.`delete node with one right child`() + val expectedKeys = listOf(444, 222, 111, 333, 555, 666, 1000) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `delete node with one left child`() { + super.`delete node with one left child`() + val expectedKeys = listOf(444, 222, 111, 333, 555, 666, 676) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } + + @Test + override fun `delete node with two children`() { + super.`delete node with two children`() + val expectedKeys = listOf(444, 222, 111, 333, 666, 777) + val actualKeys = bigTree.preorderTraverse() + assertEquals(expectedKeys, actualKeys) + } +} diff --git a/lib/src/test/kotlin/treesTests/RBTreeTest.kt b/lib/src/test/kotlin/treesTests/RBTreeTest.kt new file mode 100644 index 0000000..6900793 --- /dev/null +++ b/lib/src/test/kotlin/treesTests/RBTreeTest.kt @@ -0,0 +1,206 @@ +package treesTests + +import trees.RBTree +import nodes.RBNode +import nodes.Color +import org.junit.jupiter.api.Assertions.assertEquals +import kotlin.test.Test + +class RBTreeTest : AbstractTest, RBTree>() { + + override fun createNewTree(): RBTree = RBTree() + + @Test + fun `traverse RB tree`() { + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(666, Color.BLACK), Pair(555, Color.RED), Pair(777, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + override fun `insert root in empty tree`() { + super.`insert root in empty tree`() + val expectedKeysAndColors = listOf(Pair(100, Color.BLACK)) + val actualKeysAndColors = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + override fun `insert node with existing key`() { + super.`insert node with existing key`() + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(666, Color.BLACK), Pair(555, Color.RED), Pair(777, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + override fun `delete node with non-existing key`() { + super.`delete node with non-existing key`() + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(666, Color.BLACK), Pair(555, Color.RED), Pair(777, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + override fun `delete node from empty tree`() { + super.`delete node from empty tree`() + val expectedKeysAndColorsAndColors: List> = listOf() + val actualKeysAndColorsAndColors = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndColorsAndColors, actualKeysAndColorsAndColors) + } + + @Test + fun `insert node with BLACK parent`() { + emptyTree = createNewTree() + emptyTree.insert(2, "hi") + emptyTree.insert(3, "bye") + val expectedKeysAndColors = listOf(Pair(2, Color.BLACK), Pair(3, Color.RED)) + val actualKeysAndColors = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + /* case 4: uncle is black, parent is red; grandparent, parent and node form a "triangle" + * G G + * / \ + * P - left triangle P - right triangle + * \ / + * N N + * + */ + @Test + fun `insert node into left triangle`() { + emptyTree = createNewTree() + emptyTree.insert(50, "Apple") + emptyTree.insert(30, "Banana") + emptyTree.insert(40, "Grape") + val expectedKeysAndColorsAndColors = listOf(Pair(40, Color.BLACK), Pair(30, Color.RED), Pair(50, Color.RED)) + val actualKeysAndColorsAndColors: List> = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndColorsAndColors, actualKeysAndColorsAndColors) + } + + @Test + fun `insert node into right triangle`() { + emptyTree = createNewTree() + emptyTree.insert(50, "Apple") + emptyTree.insert(60, "Banana") + emptyTree.insert(55, "Grape") + val expectedKeysAndColorsAndColors = listOf(Pair(55, Color.BLACK), Pair(50, Color.RED), Pair(60, Color.RED)) + val actualKeysAndColorsAndColors: List> = emptyTree.preorderTraverse() + assertEquals(expectedKeysAndColorsAndColors, actualKeysAndColorsAndColors) + } + + @Test + fun `insert node into right line`() { + bigTree.insert(1111, "hi") + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(666, Color.RED), Pair(555, Color.BLACK), Pair(777, Color.BLACK), Pair(1111, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `insert node into left line`() { + bigTree.insert(455, "hi") + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(666, Color.RED), Pair(555, Color.BLACK), Pair(455, Color.RED), Pair(777, Color.BLACK)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete RED node with two children (left subtree & right leaf)`() { + bigTree.insert(565, "hi") + bigTree.delete(666) + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(565, Color.RED), Pair(555, Color.BLACK), Pair(777, Color.BLACK)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete RED node with no children`() { + bigTree.delete(777) + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(666, Color.BLACK), Pair(555, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete BLACK node with one right RED child`() { + bigTree.delete(555) + bigTree.delete(666) + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(777, Color.BLACK)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete BLACK node with one left RED child`() { + bigTree.delete(777) + bigTree.delete(666) + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.BLACK), Pair(111, Color.RED), Pair(333, Color.RED), Pair(555, Color.BLACK)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete BLACK node with no children and RED sibling`() { + bigTree.insert(565, "hi") + bigTree.delete(111) + bigTree.delete(333) + bigTree.delete(222) + val expectedKeysAndColors = listOf(Pair(666, Color.BLACK), Pair(555, Color.RED), Pair(444, Color.BLACK), Pair(565, Color.BLACK), Pair(777, Color.BLACK)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete BLACK node with two children (left subtree & right leaf)`() { + bigTree.delete(555) + bigTree.delete(777) + bigTree.delete(444) + val expectedKeysAndColors = listOf(Pair(222, Color.BLACK), Pair(111, Color.BLACK), Pair(666, Color.BLACK), Pair(333, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete left BLACK node with RED nephew`() { + bigTree.insert(235, "hi") + bigTree.delete(111) + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(235, Color.RED), Pair(222, Color.BLACK), Pair(333, Color.BLACK), Pair(666, Color.BLACK), Pair(555, Color.RED), Pair(777, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete BLACK node with no children and black sibling`() { + bigTree.delete(555) + bigTree.delete(777) + bigTree.delete(111) + bigTree.delete(333) + bigTree.delete(666) + val expectedKeysAndColors = listOf(Pair(444, Color.BLACK), Pair(222, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete BLACK node with no children and BLACK sibling which has right RED child`() { + bigTree.delete(555) + bigTree.delete(777) + bigTree.insert(55, "hi") + bigTree.delete(666) + val expectedKeysAndColors = listOf(Pair(222, Color.BLACK), Pair(111, Color.BLACK), Pair(55, Color.RED), Pair(444, Color.BLACK), Pair(333, Color.RED)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } + + @Test + fun `delete BLACK node with no children and BLACK sibling which has left RED child`() { + bigTree.delete(111) + bigTree.delete(333) + bigTree.delete(777) + bigTree.delete(222) + val expectedKeysAndColors = listOf(Pair(555, Color.BLACK), Pair(444, Color.BLACK), Pair(666, Color.BLACK)) + val actualKeysAndColors = bigTree.preorderTraverse() + assertEquals(expectedKeysAndColors, actualKeysAndColors) + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b87aac9 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,6 @@ +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0' +} +rootProject.name = 'trees-5' +include("lib") +