Chapters

Hide chapters

Data Structures & Algorithms in Swift

Fourth Edition · iOS 15 · Swift 5.5 · Xcode 13

14. Binary Search Trees
Written by Kelvin Lau

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

A binary search tree, or BST, is a data structure that facilitates fast lookup, insert and removal operations. Consider the following decision tree where picking a side forfeits all the possibilities of the other side, cutting the problem in half.

no yes no yes no yes no yes yes no Should I go the gym? Did I go yesterday? Did I go jogging yesterday? Am I still feeling sore? Did I run 5km? Go to the gym Go to the gym Go to sleep Rest for the day Break Go to the gym Did you slack off in the last session?

Once you make a decision and choose a branch, there is no looking back. You keep going until you make a final decision at a leaf node. Binary trees let you do the same thing. Specifically, a binary search tree imposes two rules on the binary tree you saw in the previous chapter:

  • The value of a left child must be less than the value of its parent.
  • Consequently, the value of a right child must be greater than or equal to the value of its parent.

Binary search trees use this property to save you from performing unnecessary checking. As a result, lookup, insert and removal have an average time complexity of O(log n), which is considerably faster than linear data structures such as arrays and linked lists.

In this chapter, you’ll learn about the benefits of the BST relative to an array and, as usual, implement the data structure from scratch.

Case study: array vs. BST

To illustrate the power of using a BST, you’ll look at some common operations and compare the performance of arrays against the binary search tree.

Consider the following two collections:

1 25 88 18 45 4 40 105 20 77 70 40 18 77 1 20 70 105 4 25 45 88

Lookup

There’s only one way to do element lookups for an unsorted array. You need to check every element in the array from the start:

5 85 67 19 85 8 75 249 49 97 46
Zoeqvhekq muq 493

73 93 00 87 375 32 27 3 94 9 74
Keigvbong fex 266

Insertion

The performance benefits for the insertion operation follow a similar story. Assume you want to insert 0 into a collection:

2 47 10 54 27 9 22 380 83 39 57 1 5 84 77 86 19 2 13 119 81 10 97
Ummickidj 3 at hoqfer ohxuw

09 59 09 12 826 87 32 2 55 0 83

Removal

Similar to insertion, removing an element in an array also triggers a shuffling of elements:

0 51 29 48 13 1 71 749 71 68 00 7 25 28 20 1 33 527 95 61 62 wututi 58
Fopevumg 04 vdah lwo aftil

21 48 30 71 292 46 88 8 08 0 31

Implementation

Open up the starter project for this chapter. In it, you’ll find the BinaryNode type that you created in the previous chapter. Create a new file named BinarySearchTree.swift and add the following inside the file:

Inserting elements

Per the rules of the BST, nodes of the left child must contain values less than the current node. Nodes of the right child must contain values greater than or equal to the current node. You’ll implement the insert method while respecting these rules.

1 9 0 5 4 8 5 1 9 0 yuzucsim ohvasopdih

5 9 4 8 8 6 3 0 1 7 anxokodpuv qucofziq 8 5 5

Finding elements

Finding an element in a BST requires you to traverse through its nodes. It’s possible to come up with a relatively simple implementation by using the existing traversal mechanisms that you learned about in the previous chapter.

Optimizing contains

You can rely on the rules of the BST to avoid needless comparisons. Back in BinarySearchTree.swift, update the contains method to the following:

Removing elements

Removing elements is a little more tricky, as you need to handle a few different scenarios.

Case 1: Leaf node

Removing a leaf node is straightforward; simply detach the leaf node.

3 1 7 3 1 2
Cicehelw 1

Case 2: Nodes with one child

When removing nodes with one child, you’ll need to reconnect that one child with the rest of the tree:

7 2 5 9 3 6
Sujixewn 4, gneyz muh 7 xkeqx

Case 3: Nodes with two children

Nodes with two children are a bit more complicated, so a more complex example tree will better illustrate how to handle this situation. Assume that you have the following tree and that you want to remove the value 25:

77 Xobaji 08 86 43 53 59 44 82 59 66 26 76 22 31

79 22 60 14 17 98 99 69 18 79 55 30

05 Cihkukab hiwii 75 01 86 09 92 46 01 66 49 81 35 95

96 01 38 16 85 84 94 83 50 29 00 32 76

Implementation

Open up BinarySearchTree.swift to implement remove. Add the following code at the bottom of the file:

Key points

  • The binary search tree is a powerful data structure for holding sorted data.
  • Elements of the binary search tree must be comparable. You can achieve this using a generic constraint or by supplying closures to perform the comparison.
  • The time complexity for insert, remove and contains methods in a BST is O(log n).
  • Performance will degrade to O(n) as the tree becomes unbalanced. This is undesirable, so you’ll learn about a self-balancing binary search tree called the AVL tree in Chapter 16.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now