feat: add Swift codes for binary_tree_traversal article

This commit is contained in:
nuomi1
2023-01-19 00:12:54 +08:00
parent 46429bcb23
commit d52b60804b
5 changed files with 191 additions and 1 deletions

View File

@@ -0,0 +1,42 @@
/**
* File: binary_tree_bfs.swift
* Created Time: 2023-01-18
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
func hierOrder(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(list: [1, 2, 3, 4, 5, 6, 7])!
print("\n初始化二叉树\n")
PrintUtil.printTree(root: node)
/* */
let list = hierOrder(root: node)
print("\n层序遍历的结点打印序列 = \(list)")
}
}

View File

@@ -0,0 +1,70 @@
/**
* 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)")
}
}