Files
hello-algo/ja/codes/swift/chapter_tree/binary_tree_bfs.swift
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

43 lines
1.3 KiB
Swift
Raw Permalink 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_bfs.swift
* Created Time: 2023-01-18
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* レベル順走査 */
func levelOrder(root: TreeNode) -> [Int] {
// キューを初期化し、根ノードを追加する
var queue: [TreeNode] = [root]
// 走査順序を保存するリストを初期化する
var list: [Int] = []
while !queue.isEmpty {
let node = queue.removeFirst() // キューからデキューする
list.append(node.val) // ノードの値を保存する
if let left = node.left {
queue.append(left) // 左の子ノードをエンキューする
}
if let right = node.right {
queue.append(right) // 右の子ノードをエンキューする
}
}
return list
}
@main
enum BinaryTreeBFS {
/* 実行用コード */
static func main() {
/* 二分木を初期化する */
// ここでは配列から二分木を直接生成する関数を使う
let node = TreeNode.listToTree(arr: [1, 2, 3, 4, 5, 6, 7])!
print("\n二分木を初期化する\n")
PrintUtil.printTree(root: node)
/* レベル順走査 */
let list = levelOrder(root: node)
print("\nレベル順走査で表示するノードの順序 = \(list)")
}
}