hello-algo/codes/kotlin/chapter_backtracking/preorder_traversal_i_compact.kt
curtishd 306dc019ef
Add Kotlin code for computational complexity (#1090)
* feat(kotlin):new kotlin support files

* fix(kotlin):

    reviewed the formatting, comments and so on.

* fix(kotlin): fix the indentation and format

* feat(kotlin): Add kotlin code for the backtraking chapter.

* fix(kotlin): fix incorrect output of preorder_traversal_iii_template.kt file

* fix(kotlin): simplify kotlin codes

* fix(kotlin): modify n_queens.kt for consistency.

* feat(kotlin): add kotlin code for computational complexity.

* fix(kotlin): remove iteration folder.

* fix(kotlin): remove n_queens.kt file out of folder.

* fix(kotlin): remove some folders.

* style(kotlin): modified two chapters.
2024-02-27 17:04:57 +08:00

43 lines
No EOL
916 B
Kotlin

/**
* File: preorder_traversal_i_compact.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_backtracking.preorder_traversal_i_compact
import utils.TreeNode
import utils.printTree
var res: MutableList<TreeNode>? = null
/* 前序遍历:例题一 */
fun preOrder(root: TreeNode?) {
if (root == null) {
return
}
if (root.value == 7) {
// 记录解
res!!.add(root)
}
preOrder(root.left)
preOrder(root.right)
}
/* Driver Code */
fun main() {
val root = TreeNode.listToTree(mutableListOf(1, 7, 3, 4, 5, 6, 7))
println("\n初始化二叉树")
printTree(root)
// 前序遍历
res = ArrayList()
preOrder(root)
println("\n输出所有值为 7 的节点")
val vals: MutableList<Int> = ArrayList()
for (node in res as ArrayList<TreeNode>) {
vals.add(node.value)
}
println(vals)
}