我是新手,我实现了这样的树数据结构。它工作正常。我唯一想知道的是,此解决方案中是否存在任何内存泄漏。
如果是,我该如何治愈?如果没有,我是否应该记住一个特定条件以避免或检测内存泄漏?
import Foundation
struct Queue<Element> {
var elements : [Element] = []
var isEmpty : Bool {
return elements.isEmpty
}
@discardableResult
mutating func Enqueue (_ element : Element) -> Bool{
elements.append(element)
return true
}
mutating func Dequeue() -> Element? {
return isEmpty ? nil : elements.removeFirst()
}
}
class TreeNode<T> {
var value : T
var children : [TreeNode] = []
init(_ value : T) {
self.value = value
}
func addChild(_ child : TreeNode) {
self.children.append(child)
}
}
extension TreeNode where T : Equatable{
//for depth first traversal
func forEachDepthFirst(_ visit : (TreeNode) -> Void) {
visit(self)
children.forEach {
$0.forEachDepthFirst(visit)
}
}
//for level order traversal
func forEachLevelOrder(_ visit : (TreeNode) -> Void) {
visit(self)
var queue = Queue<TreeNode>()
children.forEach {
queue.Enqueue($0)
}
while let node = queue.Dequeue() {
visit(node)
node.children.forEach { queue.Enqueue($0)}
}
}
//searching in a tree
func search(_ value : T) -> TreeNode? {
var result : TreeNode?
forEachLevelOrder { node in
if node.value == value {
result = node
}
}
return result
}
}
//操作
let coffee = TreeNode<String>("Coffee")
let hot = TreeNode<String>("Hot")
let cold = TreeNode<String>("Cold")
coffee.addChild(hot)
coffee.addChild(cold)
let cappucino = TreeNode<String>("Cappucino")
let regular = TreeNode<String>("Regular")
let americano = TreeNode<String>("Americano")
hot.addChild(cappucino)
hot.addChild(regular)
hot.addChild(americano)
let coldCoffee = TreeNode<String>("Cold Coffee")
let specialCold = TreeNode<String>("Special Cold")
cold.addChild(coldCoffee)
coldCoffee.addChild(specialCold)
//coffee.forEachDepthFirst {
// print($0.value)
//}
//coffee.forEachLevelOrder {
// print($0.value)
//}
if let searchResult = coffee.search("Special Cold") {
print(searchResult.value)
}
谢谢。