How do I implement a generic binary search tree in Swift?

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

Generic Binary Search Tree Swift Comparable Tree Structure Data Structures