hello-algo/codes/kotlin/utils/PrintUtil.kt
curtishd 5ec5ef9af0
Add kotlin code for the utils file (#1175)
* feat(kotlin): add kotlin code for utils file.

* Update ListNode.kt

* Update PrintUtil.kt

---------

Co-authored-by: Yudong Jin <krahets@163.com>
2024-03-25 19:15:40 +08:00

106 lines
2.1 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: PrintUtil.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package utils
import java.util.*
class Trunk(var prev: Trunk?, var str: String)
/* 打印矩阵Array */
fun <T> printMatrix(matrix: Array<Array<T>>) {
println("[")
for (row in matrix) {
println(" $row,")
}
println("]")
}
/* 打印矩阵List */
fun <T> printMatrix(matrix: List<List<T>>) {
println("[")
for (row in matrix) {
println(" $row,")
}
println("]")
}
/* 打印链表 */
fun printLinkedList(h: ListNode?) {
var head = h
val list = ArrayList<String>()
while (head != null) {
list.add(head.value.toString())
head = head.next
}
println(list.joinToString(separator = " -> "))
}
/* 打印二叉树 */
fun printTree(root: TreeNode?) {
printTree(root, null, false)
}
/**
* 打印二叉树
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
fun printTree(root: TreeNode?, prev: Trunk?, isRight: Boolean) {
if (root == null) {
return
}
var prevStr = " "
val trunk = Trunk(prev, prevStr)
printTree(root.right, trunk, true)
if (prev == null) {
trunk.str = "———"
} else if (isRight) {
trunk.str = "/———"
prevStr = " |"
} else {
trunk.str = "\\———"
prev.str = prevStr
}
showTrunks(trunk)
println(" ${root.value}")
if (prev != null) {
prev.str = prevStr
}
trunk.str = " |"
printTree(root.left, trunk, false)
}
fun showTrunks(p: Trunk?) {
if (p == null) {
return
}
showTrunks(p.prev)
print(p.str)
}
/* 打印哈希表 */
fun <K, V> printHashMap(map: Map<K, V>) {
for ((key, value) in map) {
println(key.toString() + " -> " + value)
}
}
/* 打印堆 */
fun printHeap(queue: Queue<Int>?) {
val list = queue?.let { ArrayList(it) }
print("堆的数组表示:")
println(list)
println("堆的树状表示:")
val root = list?.let { TreeNode.listToTree(it) }
printTree(root)
}