Recursion

Binary Search Tree

Lesson

A Binary Search Tree is just a Sorted Array, but in the shape of a tree. This lets you insert/delete elements in O(log⁡n)O(\log n) time, which is better than a Sorted Array's O(n)O(n) insert/delete time.

Binary Search Tree - image

The definition of a BST is that the values in the left subtree are all smaller than the current value, and the values in the right subtree are all larger than the current value.

Binary Search Tree - image

Question: Is the value "7" allowed where the arrow is drawn in the below tree?

Binary Search Tree - image

Answer:

Search Time Complexity O(log⁡n)O(\log n), assuming the tree is balanced. Balanced trees have a height of O(log⁡n)O(\log n), and you need to step to the bottom of the tree worst-case.

Read Time Complexity O(log⁡n)O(\log n), assuming the tree is balanced.

Insert/Delete Time Complexity O(log⁡n)O(\log n), assuming the tree is balanced.

Create Time Complexity O(nlog⁡n)O(n \log n). You can sort your elements and then turn the sorted array into a BST, or you can add elements to an empty BST one at a time. Either way, this is O(nlog⁡n)O(n \log n).

Comparison between Sorted Array and BST:

Sorted Array                Balanced BSTSearch TimeO(log n)                O(log n)Read TimeO(1)                          O(log n)Insert/Delete TimeO(n)                          O(log n)\notag \def\t#1{\text{#1}} \def\ss{\;\;\;\;\;\;\;\;} \begin{align*} &\t{} &\t{Sorted Array}\ss &\t{Balanced BST} \\[10bp] &\text{Search Time} &\t{O(log n)}\ss &\t{O(log n)} \\ &\t{Read Time} &\t{O(1)}\ss\;\;\;\;\; &\t{O(log n)} \\ &\t{Insert/Delete Time} &\t{O(n)}\ss\;\;\;\;\; &\t{O(log n)} \\ \end{align*}

You can see why balanced BSTs are preferred when you have to insert/modify/delete elements: you avoid the O(n)O(n) write cost of the array.

Self-Balancing BSTs

There are ways of keeping a BST balanced at all times, called "self-balancing BSTs". A few popular ones are B-trees, Red-black trees (guaranteed balanced), and Treaps (probabilistically balanced). Implementation details vary, but the general idea is that they come with an invariant that keeps them roughly balanced, and when an element is added/removed/changed, other elements are shifted around to preserve the invariant.

You rarely need to pull out a self-balancing BST in an interview problem (you might be given a normal BST to work with, though!). However, it's good to know that on the job you can use a BST without manually having to balance it.

Mark as Completed:
Submits:
test
Test your code to get an output here!