hello-algo/codes/swift/chapter_backtracking/preorder_traversal_i_compact.swift
nuomi1 9ab4b0b15c
Feature/array representation of tree swift (#649)
* refactor: encode & decode Tree

* style: build warning

* feat: add Swift codes for array_representation_of_tree article
2023-07-24 12:46:48 +08:00

43 lines
892 B
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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