I am learning tree on Leetcode. Need to prepare the testing data.
It is easy to convert the array to an organized node, where its elements are integers.
such as [3, 9, 20, 15, 7]
Here is my code:
extension Array where Element == Int{
func arrayToTree() -> TreeNode{
var nodes = [TreeNode]()
for num in 0..<self.count{
nodes.append(TreeNode(self[num]))
}
var i = 0
repeat{
nodes[i].left = nodes[2 * i + 1]
if self.count > 2 * i + 2 {
nodes[i].right = nodes[2 * i + 2]
}
i+=1
}while i < (self.count)/2
return nodes.first!
}
}
When the last level contains some nils , such as [3, 9, 20, nil, nil, 15, 7]
Here is the code:
extension Array where Element == Int?{
func arrayToTree() -> TreeNode?{
guard self.count > 0 else{
return nil
}
var nodes = [TreeNode?]()
for num in 0..<self.count{
if let num = self[num]{
nodes.append(TreeNode(num))
}
else{
nodes.append(nil)
}
}
var i = 0
repeat {
nodes[i]?.left = nodes[2 * i + 1]
if self.count > 2 * i + 2 {
nodes[i]?.right = nodes[2 * i + 2]
}
i += 1
} while i < (self.count) / 2
return nodes.first!
}
}
How can I refactor this?
Such as combine them together using Swift Generic with some Protocol.