Implementing a generic binary search tree (BST) in Swift allows you to create a tree structure that can store any type of data that conforms to the Comparable protocol. Below is an example of how to create a simple generic binary search tree.
// Generic Binary Search Tree
class TreeNode {
var value: T
var left: TreeNode?
var right: TreeNode?
init(value: T) {
self.value = value
self.left = nil
self.right = nil
}
}
class BinarySearchTree {
private var root: TreeNode?
func insert(value: T) {
root = insertRecursively(root, value: value)
}
private func insertRecursively(_ node: TreeNode?, value: T) -> TreeNode {
guard let node = node else {
return TreeNode(value: value)
}
if value < node.value {
node.left = insertRecursively(node.left, value: value)
} else if value > node.value {
node.right = insertRecursively(node.right, value: value)
}
return node
}
func search(value: T) -> Bool {
return searchRecursively(root, value: value)
}
private func searchRecursively(_ node: TreeNode?, value: T) -> Bool {
guard let node = node else { return false }
if value < node.value {
return searchRecursively(node.left, value: value)
} else if value > node.value {
return searchRecursively(node.right, value: value)
} else {
return true
}
}
}
// Example usage
let bst = BinarySearchTree()
bst.insert(value: 10)
bst.insert(value: 5)
bst.insert(value: 15)
print(bst.search(value: 5)) // Output: true
print(bst.search(value: 20)) // Output: false
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?