Skip to content

Instantly share code, notes, and snippets.

@Mintri1199
Created December 5, 2019 23:57
Show Gist options
  • Save Mintri1199/83c78ba9a4b91a1c7f3c011d815cd5d5 to your computer and use it in GitHub Desktop.
Save Mintri1199/83c78ba9a4b91a1c7f3c011d815cd5d5 to your computer and use it in GitHub Desktop.
class PrefixTreeNode {
var data: String?
var weight: Int = 0
var userWeight: Int?
var children: [PrefixTreeNode?] = Array(repeating: nil, count: 26)
func isEmpty() -> Bool {
return self.numberOfChildren() == 0
}
func numberOfChildren() -> Int {
// Return the number of non nil children in the array
return children.reduce(0, { result, child in return child == nil ? result : result + 1 })
}
private func hasChild(_ char: Character) -> Bool {
// Return a bool whether the node has a child for the given character
if char.isLetter {
let value = self.charToInt(char)
return self.children[value - 65] != nil
} else {
return false
}
}
func getChild(_ char: Character) -> PrefixTreeNode? {
// Return the child node for the given character
return self.hasChild(char) ? self.children[self.charToInt(char) - 65] : nil
}
func addChild(_ char: Character, childNode: PrefixTreeNode) {
if !self.hasChild(char) && char.isLetter {
self.children[self.charToInt(char) - 65] = childNode
}
}
private func charToInt(_ char: Character) -> Int {
if let value = char.asciiValue {
return Int(value)
} else {
return -1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment