create a binary search tree and insert 1,2,3,4 in it in swift

To create a binary search tree in Swift, we first need to define a Node structure:

main.swift
class Node<T: Comparable> {
    var value: T
    var leftChild: Node<T>?
    var rightChild: Node<T>?
    
    init(value: T) {
        self.value = value
    }
}
163 chars
10 lines

This defines a Node that can hold a value and has pointers to its left and right child.

To insert values into the tree, we can define a insert method in a separate BinarySearchTree class:

main.swift
class BinarySearchTree<T: Comparable> {
    var root: Node<T>?
    
    func insert(value: T) {
        let newNode = Node(value: value)
        
        if let node = root {
            insertHelper(node: node, newNode: newNode)
        } else {
            root = newNode
        }
    }
    
    private func insertHelper(node: Node<T>, newNode: Node<T>) {
        if newNode.value < node.value {
            if let leftChild = node.leftChild {
                insertHelper(node: leftChild, newNode: newNode)
            } else {
                node.leftChild = newNode
            }
        } else {
            if let rightChild = node.rightChild {
                insertHelper(node: rightChild, newNode: newNode)
            } else {
                node.rightChild = newNode
            }
        }
    }
}
815 chars
30 lines

In the insert method, we first create a new node with the desired value. If there is no root node, we assign the new node as the root. If there is already a root node, we call a private helper method to handle the insertion.

The insertHelper method compares the value of the new node with the current node. If the new value is less than the current node's value, we move to the left child node. If there is no left child, we assign the new node as the left child. If the new value is greater than or equal to the current node's value, we move to the right child node. If there is no right child, we assign the new node as the right child.

We can then create a new BinarySearchTree instance and insert the values 1, 2, 3, and 4 like so:

main.swift
let bst = BinarySearchTree<Int>()
bst.insert(value: 1)
bst.insert(value: 2)
bst.insert(value: 3)
bst.insert(value: 4)
118 chars
6 lines

This creates a binary search tree with 4 nodes, where the root node holds the value 1 and has a right child node with the value 2, and the right child node has a right child node with the value 3, and the right child of that node has a right child node with the value 4.

gistlibby LogSnag