mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-30 22:03:47 +08:00
build
This commit is contained in:
@ -1172,8 +1172,8 @@ comments: true
|
||||
=== "Kotlin"
|
||||
|
||||
```kotlin title="array_binary_tree.kt"
|
||||
/* 数组表示下的二叉树类 */
|
||||
class ArrayBinaryTree(val tree: List<Int?>) {
|
||||
/* 构造方法 */
|
||||
class ArrayBinaryTree(val tree: MutableList<Int?>) {
|
||||
/* 列表容量 */
|
||||
fun size(): Int {
|
||||
return tree.size
|
||||
@ -1202,11 +1202,12 @@ comments: true
|
||||
}
|
||||
|
||||
/* 层序遍历 */
|
||||
fun levelOrder(): List<Int?> {
|
||||
val res = ArrayList<Int?>()
|
||||
fun levelOrder(): MutableList<Int?> {
|
||||
val res = mutableListOf<Int?>()
|
||||
// 直接遍历数组
|
||||
for (i in 0..<size()) {
|
||||
if (value(i) != null) res.add(value(i))
|
||||
if (value(i) != null)
|
||||
res.add(value(i))
|
||||
}
|
||||
return res
|
||||
}
|
||||
@ -1214,34 +1215,38 @@ comments: true
|
||||
/* 深度优先遍历 */
|
||||
fun dfs(i: Int, order: String, res: MutableList<Int?>) {
|
||||
// 若为空位,则返回
|
||||
if (value(i) == null) return
|
||||
if (value(i) == null)
|
||||
return
|
||||
// 前序遍历
|
||||
if ("pre" == order) res.add(value(i))
|
||||
if ("pre" == order)
|
||||
res.add(value(i))
|
||||
dfs(left(i), order, res)
|
||||
// 中序遍历
|
||||
if ("in" == order) res.add(value(i))
|
||||
if ("in" == order)
|
||||
res.add(value(i))
|
||||
dfs(right(i), order, res)
|
||||
// 后序遍历
|
||||
if ("post" == order) res.add(value(i))
|
||||
if ("post" == order)
|
||||
res.add(value(i))
|
||||
}
|
||||
|
||||
/* 前序遍历 */
|
||||
fun preOrder(): List<Int?> {
|
||||
val res = ArrayList<Int?>()
|
||||
fun preOrder(): MutableList<Int?> {
|
||||
val res = mutableListOf<Int?>()
|
||||
dfs(0, "pre", res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* 中序遍历 */
|
||||
fun inOrder(): List<Int?> {
|
||||
val res = ArrayList<Int?>()
|
||||
fun inOrder(): MutableList<Int?> {
|
||||
val res = mutableListOf<Int?>()
|
||||
dfs(0, "in", res)
|
||||
return res
|
||||
}
|
||||
|
||||
/* 后序遍历 */
|
||||
fun postOrder(): List<Int?> {
|
||||
val res = ArrayList<Int?>()
|
||||
fun postOrder(): MutableList<Int?> {
|
||||
val res = mutableListOf<Int?>()
|
||||
dfs(0, "post", res)
|
||||
return res
|
||||
}
|
||||
|
Reference in New Issue
Block a user