To create a binary search tree in Swift, we first need to define a Node
structure:
main.swift163 chars10 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.swift815 chars30 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.swift118 chars6 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