Skip to content

Instantly share code, notes, and snippets.

@WonderJeffy
Created December 27, 2024 08:00
Show Gist options
  • Save WonderJeffy/f674bfd9b86d68da543af24f28b3804f to your computer and use it in GitHub Desktop.
Save WonderJeffy/f674bfd9b86d68da543af24f28b3804f to your computer and use it in GitHub Desktop.
二叉树
/// 二叉树节点
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
class func makeTree(_ array:[Int?]) -> TreeNode? {
let count = array.count
func plant(_ index:Int) -> TreeNode? {
guard index < count, let value = array[index] else {
return nil
}
let node = TreeNode.init(value)
node.left = plant(index*2+1)
node.right = plant(index*2+2)
return node
}
return plant(0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment