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/zh-hant/codes/swift/chapter_tree/binary_tree_dfs.swift

71 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 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(arr: [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)")
}
}