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/utils/TreeNode.swift

72 lines
2.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: 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
}
}