hello-algo/codes/swift/chapter_tree/binary_tree_dfs.swift
Yudong Jin 1c8b7ef559
refactor: Replace 结点 with 节点 (#452)
* Replace 结点 with 节点
Update the footnotes in the figures

* Update mindmap

* Reduce the size of the mindmap.png
2023-04-09 04:32:17 +08:00

70 lines
1.7 KiB
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: binary_tree_dfs.swift
* Created Time: 2023-01-18
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
//
var list: [Int] = []
/* */
func preOrder(root: TreeNode?) {
guard let root = root else {
return
}
// 访 -> ->
list.append(root.val)
preOrder(root: root.left)
preOrder(root: root.right)
}
/* */
func inOrder(root: TreeNode?) {
guard let root = root else {
return
}
// 访 -> ->
inOrder(root: root.left)
list.append(root.val)
inOrder(root: root.right)
}
/* */
func postOrder(root: TreeNode?) {
guard let root = root else {
return
}
// 访 -> ->
postOrder(root: root.left)
postOrder(root: root.right)
list.append(root.val)
}
@main
enum BinaryTreeDFS {
/* Driver Code */
static func main() {
/* */
//
let root = TreeNode.listToTree(list: [1, 2, 3, 4, 5, 6, 7])!
print("\n初始化二叉树\n")
PrintUtil.printTree(root: root)
/* */
list.removeAll()
preOrder(root: root)
print("\n前序遍历的节点打印序列 = \(list)")
/* */
list.removeAll()
inOrder(root: root)
print("\n中序遍历的节点打印序列 = \(list)")
/* */
list.removeAll()
postOrder(root: root)
print("\n后序遍历的节点打印序列 = \(list)")
}
}