You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_backtracking/preorder_traversal_iii_temp...

78 lines
2.2 KiB

/**
* File: preorder_traversal_iii_template.swift
* Created Time: 2023-04-30
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
func isSolution(state: [TreeNode]) -> Bool {
!state.isEmpty && state.last!.val == 7
}
/* */
func recordSolution(state: [TreeNode], res: inout [[TreeNode]]) {
res.append(state)
}
/* */
func isValid(state: [TreeNode], choice: TreeNode?) -> Bool {
choice != nil && choice!.val != 3
}
/* */
func makeChoice(state: inout [TreeNode], choice: TreeNode) {
state.append(choice)
}
/* */
func undoChoice(state: inout [TreeNode], choice: TreeNode) {
state.removeLast()
}
/* */
func backtrack(state: inout [TreeNode], choices: [TreeNode], res: inout [[TreeNode]]) {
//
if isSolution(state: state) {
recordSolution(state: state, res: &res)
return
}
//
for choice in choices {
//
if isValid(state: state, choice: choice) {
//
makeChoice(state: &state, choice: choice)
//
backtrack(state: &state, choices: [choice.left, choice.right].compactMap { $0 }, res: &res)
// 退
undoChoice(state: &state, choice: choice)
}
}
}
@main
enum PreorderTraversalIIITemplate {
/* Driver Code */
static func main() {
let root = TreeNode.listToTree(list: [1, 7, 3, 4, 5, 6, 7])
print("\n初始化二叉树")
PrintUtil.printTree(root: root)
//
var state: [TreeNode] = []
var res: [[TreeNode]] = []
backtrack(state: &state, choices: [root].compactMap { $0 }, res: &res)
print("\n输出所有根节点到节点 7 的路径,且路径中不包含值为 3 的节点")
for path in res {
var vals: [Int] = []
for node in path {
vals.append(node.val)
}
print(vals)
}
}
}