2024-02-21 01:57:41 +08:00
|
|
|
/**
|
|
|
|
* File: preorder_traversal_iii_compact.kt
|
|
|
|
* Created Time: 2024-01-25
|
|
|
|
* Author: curtishd (1023632660@qq.com)
|
|
|
|
*/
|
|
|
|
|
|
|
|
package chapter_backtracking.preorder_traversal_iii_compact
|
|
|
|
|
|
|
|
import utils.TreeNode
|
|
|
|
import utils.printTree
|
|
|
|
|
|
|
|
var path: MutableList<TreeNode>? = null
|
2024-04-07 01:31:58 +08:00
|
|
|
var res: MutableList<MutableList<TreeNode>>? = null
|
2024-02-21 01:57:41 +08:00
|
|
|
|
|
|
|
/* 前序遍历:例题三 */
|
|
|
|
fun preOrder(root: TreeNode?) {
|
|
|
|
// 剪枝
|
2024-04-10 18:09:43 +08:00
|
|
|
if (root == null || root._val == 3) {
|
2024-02-21 01:57:41 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
// 尝试
|
|
|
|
path!!.add(root)
|
2024-04-10 18:09:43 +08:00
|
|
|
if (root._val == 7) {
|
2024-02-21 01:57:41 +08:00
|
|
|
// 记录解
|
2024-04-07 01:31:58 +08:00
|
|
|
res!!.add(path!!.toMutableList())
|
2024-02-21 01:57:41 +08:00
|
|
|
}
|
|
|
|
preOrder(root.left)
|
|
|
|
preOrder(root.right)
|
|
|
|
// 回退
|
|
|
|
path!!.removeAt(path!!.size - 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
fun main() {
|
|
|
|
val root = TreeNode.listToTree(mutableListOf(1, 7, 3, 4, 5, 6, 7))
|
|
|
|
println("\n初始化二叉树")
|
|
|
|
printTree(root)
|
|
|
|
|
|
|
|
// 前序遍历
|
2024-04-07 01:31:58 +08:00
|
|
|
path = mutableListOf()
|
|
|
|
res = mutableListOf()
|
2024-02-21 01:57:41 +08:00
|
|
|
preOrder(root)
|
|
|
|
|
|
|
|
println("\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点")
|
2024-04-07 01:31:58 +08:00
|
|
|
for (path in res!!) {
|
2024-04-10 18:09:43 +08:00
|
|
|
val _vals = mutableListOf<Int>()
|
2024-02-21 01:57:41 +08:00
|
|
|
for (node in path) {
|
2024-04-10 18:09:43 +08:00
|
|
|
_vals.add(node._val)
|
2024-02-21 01:57:41 +08:00
|
|
|
}
|
2024-04-10 18:09:43 +08:00
|
|
|
println(_vals)
|
2024-02-21 01:57:41 +08:00
|
|
|
}
|
|
|
|
}
|