Created
December 27, 2024 08:00
-
-
Save WonderJeffy/f674bfd9b86d68da543af24f28b3804f to your computer and use it in GitHub Desktop.
二叉树
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 二叉树节点 | |
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