Skip to content

Commit

Permalink
feat(tree): insert node in bst
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Jul 19, 2024
1 parent 0167214 commit 0118a34
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ class BinarySearchTree<T : Comparable<T>>(private var root: BinaryTreeNode<T>? =
this += i
}

fun root(): BinaryTreeNode<T>? {
return root
}

override fun height(): Int {
if (root == null) {
return 0
Expand All @@ -27,44 +31,30 @@ class BinarySearchTree<T : Comparable<T>>(private var root: BinaryTreeNode<T>? =
return heightHelper(root)
}


/**
* Inserts a Tree node into this Binary Search Tree
*/
override fun insertTreeNode(data: T): BinaryTreeNode<T>? {
if (this.root == null) {
return BinaryTreeNode(data)
}

var parent = this.root
val dummy = this.root

while (this.root != null) {
parent = this.root

if (data != null) {
if (data < this.root!!.data) {
this.root = this.root!!.left
} else {
this.root = this.root!!.right
}
}
this.root = BinaryTreeNode(data)
return this.root
}

when {
parent != null -> {
parent = BinaryTreeNode(data)
}

data < parent?.data -> {
parent?.left = BinaryTreeNode(data)
fun insertHelper(value: T, node: BinaryTreeNode<T>?): BinaryTreeNode<T> {
if (node == null) {
return BinaryTreeNode(value)
}

else -> {
parent?.right = BinaryTreeNode(data)
if (value < node.data) {
node.left = insertHelper(value, node.left)
} else {
node.right = insertHelper(value, node.right)
}
return node
}
return dummy

insertHelper(data, this.root)
return this.root
}

override fun delete(data: T): BinaryTreeNode<T>? {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.kotlinground.datastructures.trees.binarytrees.bst

import com.kotlinground.datastructures.trees.binarytrees.BinaryTreeNode
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import kotlin.test.assertNotNull

class BinarySearchTreeInsertTest {

@Test
fun `should return tree for inserted data`() {
val data = intArrayOf(8, 3, 10, 1, 6)
val searchTree = BinarySearchTree<Int>()

for (d in data) {
searchTree.insertTreeNode(d)
}

val expectedRoot = BinaryTreeNode(
data = 8,
left = BinaryTreeNode(
data = 3,
left = BinaryTreeNode(data = 1),
right = BinaryTreeNode(data = 6)
),
right = BinaryTreeNode(data = 10),
)

val actualRoot = searchTree.root()

assertNotNull(actualRoot)
assertEquals(expectedRoot, actualRoot)
assertEquals(expectedRoot.data, actualRoot.data)
assertEquals(expectedRoot.left?.data, actualRoot.left?.data)
assertEquals(expectedRoot.right?.data, actualRoot.right?.data)
assertEquals(expectedRoot.left?.left?.data, actualRoot.left?.left?.data)
assertEquals(expectedRoot.left?.right?.data, actualRoot.left?.right?.data)
}
}

0 comments on commit 0118a34

Please sign in to comment.