Skip to content

Commit 44a3d36

Browse files
veontomomaibin
authored andcommitted
Implement a binary tree (eugenp#5431)
* Add code for the article 'Java Primitives versus Objects' * Use JMH for benchmarking the primitive and wrapper classes * Uncomment the benchmarks and remove unused class * Add a binary search tree implementation * Add an example of how to use the binary tree class * Adjust the print statements
1 parent f824da9 commit 44a3d36

3 files changed

Lines changed: 505 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.datastructures
2+
3+
/**
4+
* Example of how to use the {@link Node} class.
5+
*
6+
*/
7+
fun main(args: Array<String>) {
8+
val tree = Node(4)
9+
val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11)
10+
for (key in keys) {
11+
tree.insert(key)
12+
}
13+
val node = tree.find(4)!!
14+
println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]")
15+
println("Delete node with key = 3")
16+
node.delete(3)
17+
print("Tree content after the node elimination: ")
18+
println(tree.visit().joinToString { it.toString() })
19+
}
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
package com.baeldung.datastructures
2+
3+
/**
4+
* An ADT for a binary search tree.
5+
* Note that this data type is neither immutable nor thread safe.
6+
*/
7+
class Node(
8+
var key: Int,
9+
var left: Node? = null,
10+
var right: Node? = null) {
11+
12+
/**
13+
* Return a node with given value. If no such node exists, return null.
14+
* @param value
15+
*/
16+
fun find(value: Int): Node? = when {
17+
this.key > value -> left?.find(value)
18+
this.key < value -> right?.find(value)
19+
else -> this
20+
21+
}
22+
23+
/**
24+
* Insert a given value into the tree.
25+
* After insertion, the tree should contain a node with the given value.
26+
* If the tree already contains the given value, nothing is performed.
27+
* @param value
28+
*/
29+
fun insert(value: Int) {
30+
if (value > this.key) {
31+
if (this.right == null) {
32+
this.right = Node(value)
33+
} else {
34+
this.right?.insert(value)
35+
}
36+
} else if (value < this.key) {
37+
if (this.left == null) {
38+
this.left = Node(value)
39+
} else {
40+
this.left?.insert(value)
41+
}
42+
}
43+
}
44+
45+
/**
46+
* Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged.
47+
* @param value
48+
*/
49+
fun delete(value: Int) {
50+
when {
51+
value > key -> scan(value, this.right, this)
52+
value < key -> scan(value, this.left, this)
53+
else -> removeNode(this, null)
54+
}
55+
}
56+
57+
/**
58+
* Scan the tree in the search of the given value.
59+
* @param value
60+
* @param node sub-tree that potentially might contain the sought value
61+
* @param parent node's parent
62+
*/
63+
private fun scan(value: Int, node: Node?, parent: Node?) {
64+
if (node == null) {
65+
System.out.println("value " + value
66+
+ " seems not present in the tree.")
67+
return
68+
}
69+
when {
70+
value > node.key -> scan(value, node.right, node)
71+
value < node.key -> scan(value, node.left, node)
72+
value == node.key -> removeNode(node, parent)
73+
}
74+
75+
}
76+
77+
/**
78+
* Remove the node.
79+
*
80+
* Removal process depends on how many children the node has.
81+
*
82+
* @param node node that is to be removed
83+
* @param parent parent of the node to be removed
84+
*/
85+
private fun removeNode(node: Node, parent: Node?) {
86+
node.left?.let { leftChild ->
87+
run {
88+
node.right?.let {
89+
removeTwoChildNode(node)
90+
} ?: removeSingleChildNode(node, leftChild)
91+
}
92+
} ?: run {
93+
node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent)
94+
}
95+
96+
97+
}
98+
99+
/**
100+
* Remove the node without children.
101+
* @param node
102+
* @param parent
103+
*/
104+
private fun removeNoChildNode(node: Node, parent: Node?) {
105+
parent?.let { p ->
106+
if (node == p.left) {
107+
p.left = null
108+
} else if (node == p.right) {
109+
p.right = null
110+
}
111+
} ?: throw IllegalStateException(
112+
"Can not remove the root node without child nodes")
113+
114+
}
115+
116+
/**
117+
* Remove a node that has two children.
118+
*
119+
* The process of elimination is to find the biggest key in the left sub-tree and replace the key of the
120+
* node that is to be deleted with that key.
121+
*/
122+
private fun removeTwoChildNode(node: Node) {
123+
val leftChild = node.left!!
124+
leftChild.right?.let {
125+
val maxParent = findParentOfMaxChild(leftChild)
126+
maxParent.right?.let {
127+
node.key = it.key
128+
maxParent.right = null
129+
} ?: throw IllegalStateException("Node with max child must have the right child!")
130+
131+
} ?: run {
132+
node.key = leftChild.key
133+
node.left = leftChild.left
134+
}
135+
136+
}
137+
138+
/**
139+
* Return a node whose right child contains the biggest value in the given sub-tree.
140+
* Assume that the node n has a non-null right child.
141+
*
142+
* @param n
143+
*/
144+
private fun findParentOfMaxChild(n: Node): Node {
145+
return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n }
146+
?: throw IllegalArgumentException("Right child must be non-null")
147+
148+
}
149+
150+
/**
151+
* Remove a parent that has only one child.
152+
* Removal is effectively is just coping the data from the child parent to the parent parent.
153+
* @param parent Node to be deleted. Assume that it has just one child
154+
* @param child Assume it is a child of the parent
155+
*/
156+
private fun removeSingleChildNode(parent: Node, child: Node) {
157+
parent.key = child.key
158+
parent.left = child.left
159+
parent.right = child.right
160+
}
161+
162+
fun visit(): Array<Int> {
163+
val a = left?.visit() ?: emptyArray()
164+
val b = right?.visit() ?: emptyArray()
165+
return a + arrayOf(key) + b
166+
}
167+
}

0 commit comments

Comments
 (0)