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/codes/swift/chapter_tree/binary_tree_bfs.swift

43 lines
1.1 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_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 {
/* Driver Code */
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)")
}
}