-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathFlattenBSTIntoLinkedList.kt
More file actions
36 lines (29 loc) · 987 Bytes
/
FlattenBSTIntoLinkedList.kt
File metadata and controls
36 lines (29 loc) · 987 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package algorithmdesignmanualbook.datastructures
import algorithmdesignmanualbook.print
import utils.assertIterableSameInAnyOrder
import java.util.*
class FlattenBSTIntoLinkedList(private val bst: BinarySearchTree) {
fun flatten(): LinkedList<Int> {
val linkedList = LinkedList<Int>()
inOrderTraversal(bst.getNode(), linkedList)
return linkedList
}
private fun inOrderTraversal(currentNode: Node?, holder: LinkedList<Int>) {
if (currentNode == null) {
return
}
inOrderTraversal(currentNode.left, holder)
holder.add(currentNode.value)
inOrderTraversal(currentNode.right, holder)
}
}
fun main() {
val bst1 = createBST()
// 10
// 6 15
// 4 7 12 19
bst1.print()
val flatten = FlattenBSTIntoLinkedList(bst1).flatten()
flatten.print()
assertIterableSameInAnyOrder(actual = flatten, expected = listOf(4, 6, 7, 10, 12, 15, 19))
}