I am trying to implement a BST that stores a list of words. I know that my tree structure is correct because when I try to traverse and print in order, the list prints alphabetically. However, my search function for looking for an element in a tree returns false each time.
func search(searchValue: String) -> Bool? {
if searchValue == value as! String{
return true
}
if searchValue < value as! String {
return left?.search(searchValue: searchValue)
}
if searchValue > value as! String{
return right?.search(searchValue: searchValue)
}
return false
}
The function is called in this loop. Every word not in the BST should be appended to an array misspelled. Currently no words are appended to the array. Input array is an array of all the words to be checked against the BST.
for item in arrayInput
{
let target = item.lowercased()//reversed
let inTree = tree.search(searchValue: target)
if inTree == false
{
misspelled.append(item)
}
}
More BST class for context:
public class BinarySearchTree<T: Comparable> {
fileprivate(set) public var value: T
fileprivate(set) public var parent: BinarySearchTree?
fileprivate(set) public var left: BinarySearchTree?
fileprivate(set) public var right: BinarySearchTree?
public init(value: T) {
self.value = value
}
public convenience init(array: [T]) {
precondition(array.count > 0)
self.init(value: array.first!)
for v in array.dropFirst() {
insert(value: v)
}
}
}
public func insert(value: T) {
if value < self.value {
if let left = left {
left.insert(value: value)
} else {
left = BinarySearchTree(value: value)
left?.parent = self
}
} else {
if let right = right {
right.insert(value: value)
} else {
right = BinarySearchTree(value: value)
right?.parent = self
}
}
}
parentwill cause a retain cycle, and as a result, a memory leak.