Skip to content

Instantly share code, notes, and snippets.

@Gujci
Last active June 10, 2016 10:55
Show Gist options
  • Save Gujci/5b12f7991e269b1b5fc13f2b3eff7956 to your computer and use it in GitHub Desktop.
Save Gujci/5b12f7991e269b1b5fc13f2b3eff7956 to your computer and use it in GitHub Desktop.
import Foundation
public class Tree<Element> {
public var parent: Tree<Element>?
public let value: Element
public let children: [Tree<Element>]?
init(withParent parent: Tree<Element>? = nil,value: Element,children: [Tree<Element>]? = nil) {
self.parent = parent
self.children = children
self.value = value
self.children?.forEach() { child in
child.parent = self
}
}
//MARK: - Utils
public func isLeaf() -> Bool {
return children == nil || children?.count == 0
}
public func isAnyChildrenLeaf() -> Bool {
if let validChildren = children {
for child in validChildren {
if child.isLeaf() {
return true
}
}
}
return false
}
}
public extension Tree where Element: Equatable {
public func isParentOf(other: Tree?) -> Bool {
if let parent = other?.parent?.value {
return self.value == parent
} else {
return false
}
}
public func isChildOf(other: Tree?) -> Bool {
if let otherChildren = (other?.children?.map() { return $0.value }) {
return otherChildren.find(self.value) != nil
}
return false
}
}
public func ==<T: Equatable>(lhs: Tree<T>, rhs: Tree<T>) -> Bool {
return lhs.value == rhs.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment