2024-02-21 01:57:41 +08:00
|
|
|
/**
|
|
|
|
* File: preorder_traversal_iii_template.kt
|
|
|
|
* Created Time: 2024-01-25
|
|
|
|
* Author: curtishd (1023632660@qq.com)
|
|
|
|
*/
|
|
|
|
|
|
|
|
package chapter_backtracking.preorder_traversal_iii_template
|
|
|
|
|
|
|
|
import utils.TreeNode
|
|
|
|
import utils.printTree
|
|
|
|
|
|
|
|
/* 判断当前状态是否为解 */
|
2024-04-07 01:31:58 +08:00
|
|
|
fun isSolution(state: MutableList<TreeNode?>): Boolean {
|
2024-04-10 18:09:43 +08:00
|
|
|
return state.isNotEmpty() && state[state.size - 1]?._val == 7
|
2024-02-21 01:57:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/* 记录解 */
|
2024-04-07 01:31:58 +08:00
|
|
|
fun recordSolution(state: MutableList<TreeNode?>?, res: MutableList<MutableList<TreeNode?>?>) {
|
|
|
|
res.add(state!!.toMutableList())
|
2024-02-21 01:57:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/* 判断在当前状态下,该选择是否合法 */
|
2024-04-07 01:31:58 +08:00
|
|
|
fun isValid(state: MutableList<TreeNode?>?, choice: TreeNode?): Boolean {
|
2024-04-10 18:09:43 +08:00
|
|
|
return choice != null && choice._val != 3
|
2024-02-21 01:57:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/* 更新状态 */
|
|
|
|
fun makeChoice(state: MutableList<TreeNode?>, choice: TreeNode?) {
|
|
|
|
state.add(choice)
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 恢复状态 */
|
|
|
|
fun undoChoice(state: MutableList<TreeNode?>, choice: TreeNode?) {
|
|
|
|
state.removeLast()
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 回溯算法:例题三 */
|
|
|
|
fun backtrack(
|
|
|
|
state: MutableList<TreeNode?>,
|
2024-04-07 01:31:58 +08:00
|
|
|
choices: MutableList<TreeNode?>,
|
|
|
|
res: MutableList<MutableList<TreeNode?>?>
|
2024-02-21 01:57:41 +08:00
|
|
|
) {
|
|
|
|
// 检查是否为解
|
|
|
|
if (isSolution(state)) {
|
|
|
|
// 记录解
|
|
|
|
recordSolution(state, res)
|
|
|
|
}
|
|
|
|
// 遍历所有选择
|
|
|
|
for (choice in choices) {
|
|
|
|
// 剪枝:检查选择是否合法
|
|
|
|
if (isValid(state, choice)) {
|
|
|
|
// 尝试:做出选择,更新状态
|
|
|
|
makeChoice(state, choice)
|
|
|
|
// 进行下一轮选择
|
2024-04-07 01:31:58 +08:00
|
|
|
backtrack(state, mutableListOf(choice!!.left, choice.right), res)
|
2024-02-21 01:57:41 +08:00
|
|
|
// 回退:撤销选择,恢复到之前的状态
|
|
|
|
undoChoice(state, choice)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 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
|
|
|
val res = mutableListOf<MutableList<TreeNode?>?>()
|
|
|
|
backtrack(mutableListOf(), mutableListOf(root), res)
|
2024-02-21 01:57:41 +08:00
|
|
|
|
|
|
|
println("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点")
|
|
|
|
for (path in res) {
|
2024-04-07 01:31:58 +08:00
|
|
|
val vals = mutableListOf<Int>()
|
2024-02-21 01:57:41 +08:00
|
|
|
for (node in path!!) {
|
|
|
|
if (node != null) {
|
2024-04-10 18:09:43 +08:00
|
|
|
vals.add(node._val)
|
2024-02-21 01:57:41 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
println(vals)
|
|
|
|
}
|
|
|
|
}
|