Feature/array representation of tree swift (#649)

* refactor: encode & decode Tree

* style: build warning

* feat: add Swift codes for array_representation_of_tree article
This commit is contained in:
nuomi1
2023-07-24 12:46:48 +08:00
committed by GitHub
parent c1adeb2399
commit 9ab4b0b15c
12 changed files with 200 additions and 32 deletions

View File

@ -79,7 +79,7 @@ public enum PrintUtil {
print("堆的数组表示:", terminator: "")
print(queue)
print("堆的树状表示:")
let root = TreeNode.listToTree(list: queue)
let root = TreeNode.listToTree(arr: queue)
printTree(root: root)
}

View File

@ -4,40 +4,68 @@
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
public class TreeNode {
public var val: Int //
public var height: Int //
public var left: TreeNode? //
public var right: TreeNode? //
/* */
public init(x: Int) {
val = x
height = 0
}
public static func listToTree(list: [Int]) -> TreeNode? {
let size = list.count
if size == 0 {
//
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
//
// [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
//
// / 15
// / 7
// / 3
// | \ 6
// | \ 12
// 1
// \ 2
// | / 9
// \ 4
// \ 8
/* */
private static func listToTreeDFS(arr: [Int?], i: Int) -> TreeNode? {
if i < 0 || i >= arr.count || arr[i] == nil {
return nil
}
let root = TreeNode(x: list[0])
var queue: [TreeNode] = [root]
var i = 0
while !queue.isEmpty {
let node = queue.removeFirst()
i += 1
if i >= size {
break
}
node.left = TreeNode(x: list[i])
queue.append(node.left!)
i += 1
if i >= size {
break
}
node.right = TreeNode(x: list[i])
queue.append(node.right!)
}
let root = TreeNode(x: arr[i]!)
root.left = listToTreeDFS(arr: arr, i: 2 * i + 1)
root.right = listToTreeDFS(arr: arr, i: 2 * i + 2)
return root
}
/* */
public static func listToTree(arr: [Int?]) -> TreeNode? {
listToTreeDFS(arr: arr, i: 0)
}
/* */
private static func treeToListDFS(root: TreeNode?, i: Int, res: inout [Int?]) {
if root == nil {
return
}
while i >= res.count {
res.append(nil)
}
res[i] = root?.val
treeToListDFS(root: root?.left, i: 2 * i + 1, res: &res)
treeToListDFS(root: root?.right, i: 2 * i + 2, res: &res)
}
/* */
public static func treeToList(root: TreeNode?) -> [Int?] {
var res: [Int?] = []
treeToListDFS(root: root, i: 0, res: &res)
return res
}
}