hello-algo/codes/swift/utils/TreeNode.swift
nuomi1 9ab4b0b15c
Feature/array representation of tree swift (#649)
* refactor: encode & decode Tree

* style: build warning

* feat: add Swift codes for array_representation_of_tree article
2023-07-24 12:46:48 +08:00

71 lines
2.1 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: TreeNode.swift
* Created Time: 2023-01-02
* 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
}
//
// 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: 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
}
}