AVL Tree Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓AVL Tree runs in O(log n) time and O(n) space, in Swift as in every other language.
- ✓Nothing ordered. Dictionary and Set are hashes with per-process randomised iteration order, and there is no tree of any kind in the standard library.
- ✓Model the tree as an indirect enum, which is the Swift-native way to express a recursive value type and gives you exhaustive pattern matching over the empty and node cases at every rotation.
- ✓The Swift trap: Swift will not let you write the obvious version at all. A struct or enum containing itself has no computable size, so a recursive enum is a compile error until you mark it indirect, and a struct with a var left: Node?
- ✓The indirect keyword heap-allocates each boxed case, so the enum version allocates as much as the class version while also copying on mutation.
What AVL Tree actually is
AVL Tree in Swift: what you actually reach for
Swift implementation
// "indirect" is REQUIRED: a recursive enum has no computable size
// without boxing, and the compiler rejects it outright otherwise.
// A struct with "var left: AVL?" is illegal for the same reason, with
// no keyword available to rescue it.
indirect enum AVL<Key: Comparable> {
case empty
case node(key: Key, left: AVL, right: AVL, height: Int)
var height: Int {
switch self {
case .empty: return 0
case let .node(_, _, _, h): return h
}
}
private var balance: Int {
switch self {
case .empty: return 0
case let .node(_, l, r, _): return l.height - r.height
}
}
private static func make(_ key: Key, _ l: AVL, _ r: AVL) -> AVL {
.node(key: key, left: l, right: r, height: 1 + max(l.height, r.height))
}
private func rotatedRight() -> AVL {
guard case let .node(key, .node(lk, ll, lr, _), r, _) = self else { return self }
return AVL.make(lk, ll, AVL.make(key, lr, r))
}
private func rotatedLeft() -> AVL {
guard case let .node(key, l, .node(rk, rl, rr, _), _) = self else { return self }
return AVL.make(rk, AVL.make(key, l, rl), rr)
}
func inserting(_ key: Key) -> AVL {
switch self {
case .empty:
return .node(key: key, left: .empty, right: .empty, height: 1)
case let .node(k, l, r, _):
if key == k { return self }
let grown = key < k
? AVL.make(k, l.inserting(key), r)
: AVL.make(k, l, r.inserting(key))
let b = grown.balance
guard case let .node(gk, gl, gr, _) = grown else { return grown }
if b > 1 {
return gl.balance < 0
? AVL.make(gk, gl.rotatedLeft(), gr).rotatedRight()
: grown.rotatedRight()
}
if b < -1 {
return gr.balance > 0
? AVL.make(gk, gl, gr.rotatedRight()).rotatedLeft()
: grown.rotatedLeft()
}
return grown
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for AVL Tree?
Nothing ordered. Dictionary and Set are hashes with per-process randomised iteration order, and there is no tree of any kind in the standard library.
What is the most common Swift mistake when implementing AVL Tree?
Swift will not let you write the obvious version at all. A struct or enum containing itself has no computable size, so a recursive enum is a compile error until you mark it indirect, and a struct with a var left: Node? property is rejected outright with no keyword to rescue it. This forces a design decision at the first line rather than the hundredth: indirect enum gives value semantics and pattern matching but boxes every case on the heap, while a final class gives cheap in-place mutation and reference semantics. Most other languages here let you defer that choice; Swift does not.
How does AVL Tree actually perform in Swift?
The indirect keyword heap-allocates each boxed case, so the enum version allocates as much as the class version while also copying on mutation. For a mutation-heavy tree the final class is usually faster, and marking it final matters because it lets the compiler devirtualise every method call. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.