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_comp...

53 lines
1.1 KiB

/**
* File: preorder_traversal_iii_compact.swift
* Created Time: 2023-04-30
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
var path: [TreeNode] = []
var res: [[TreeNode]] = []
/* */
func preOrder(root: TreeNode?) {
//
guard let root = root, root.val != 3 else {
return
}
//
path.append(root)
if root.val == 7 {
//
res.append(path)
}
preOrder(root: root.left)
preOrder(root: root.right)
// 退
path.removeLast()
}
@main
enum PreorderTraversalIIICompact {
/* Driver Code */
static func main() {
let root = TreeNode.listToTree(arr: [1, 7, 3, 4, 5, 6, 7])
print("\n初始化二叉树")
PrintUtil.printTree(root: root)
//
path = []
res = []
preOrder(root: root)
print("\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点")
for path in res {
var vals: [Int] = []
for node in path {
vals.append(node.val)
}
print(vals)
}
}
}