Files
hello-algo/ja/codes/swift/chapter_tree/binary_tree_dfs.swift
Yudong Jin d7b2277d2b Re-translate the Japanese version (#1871)
* Retranslate Japanese docs with GPT-5.4

* Retranslate Japanese code with GPT-5.4
2026-03-30 07:30:15 +08:00

71 lines
1.8 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(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)")
}
}