# 7.3: Discussion and Exercises

- Page ID
- 8467

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\id}{\mathrm{id}}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\kernel}{\mathrm{null}\,}\)

\( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\)

\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\)

\( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)

\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)

\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vectorC}[1]{\textbf{#1}} \)

\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)Random binary search trees have been studied extensively. Devroye [19] gives a proof of Lemma 7.1.1 and related results. There are much stronger results in the literature as well, the most impressive of which is due to Reed [64], who shows that the expected height of a random binary search tree is

\[ \alpha\ln n - \beta\ln\ln n + O(1) \nonumber\]

where \(\alpha\approx4.31107\) is the unique solution on the interval \([2,\infty)\) of the equation \(\alpha\ln((2e/\alpha))=1\) and \(\beta=\dfrac{3}{2\ln(\alpha/2)}\). Furthermore, the variance of the height is constant.

The name `Treap` was coined by Seidel and Aragon [67] who discussed `Treap`s and some of their variants. However, their basic structure was studied much earlier by Vuillemin [76] who called them Cartesian trees.

One possible space-optimization of the `Treap` data structure is the elimination of the explicit storage of the priority \(\mathtt{p}\) in each node. Instead, the priority of a node, \(\mathtt{u}\), is computed by hashing \(\mathtt{u}\)'s address in memory (in 32-bit Java, this is equivalent to hashing \(\texttt{u.hashCode()}\)). Although a number of hash functions will probably work well for this in practice, for the important parts of the proof of Lemma 7.1.1 to remain valid, the hash function should be randomized and have the min-wise independent property: For any distinct values \(x_1,\ldots,x_k\), each of the hash values \(h(x_1),\ldots,h(x_k)\) should be distinct with high probability and, for each \(i\in\{1,\ldots,k\}\),

\[ \Pr\{h(x_i) = \min\{h(x_1),\ldots,h(x_k)\}\} \le c/k \nonumber\]

for some constant \(c\). One such class of hash functions that is easy to implement and fairly fast is tabulation hashing (Section 5.2.3).

Another `Treap` variant that doesn't store priorities at each node is the randomized binary search tree of Martínez and Roura [51]. In this variant, every node, \(\mathtt{u}\), stores the size, \(\texttt{u.size}\), of the subtree rooted at \(\mathtt{u}\). Both the \(\mathtt{add(x)}\) and \(\mathtt{remove(x)}\) algorithms are randomized. The algorithm for adding \(\mathtt{x}\) to the subtree rooted at \(\mathtt{u}\) does the following:

- With probability \(1/(\mathtt{size(u)}+1)\), the value \(\mathtt{x}\) is added the usual way, as a leaf, and rotations are then done to bring \(\mathtt{x}\) up to the root of this subtree.
- Otherwise (with probability \(1-1/(\mathtt{size(u)}+1)\)), the value \(\mathtt{x}\) is recursively added into one of the two subtrees rooted at \(\texttt{u.left}\) or \(\texttt{u.right}\), as appropriate.

The first case corresponds to an \(\mathtt{add(x)}\) operation in a `Treap` where \(\mathtt{x}\)'s node receives a random priority that is smaller than any of the \(\mathtt{size(u)}\) priorities in \(\mathtt{u}\)'s subtree, and this case occurs with exactly the same probability.

Removing a value \(\mathtt{x}\) from a randomized binary search tree is similar to the process of removing from a `Treap`. We find the node, \(\mathtt{u}\), that contains \(\mathtt{x}\) and then perform rotations that repeatedly increase the depth of \(\mathtt{u}\) until it becomes a leaf, at which point we can splice it from the tree. The choice of whether to perform a left or right rotation at each step is randomized.

- With probability \(\mathtt{u\texttt{.}left\texttt{.}size/(u\texttt{.}size-1)}\), we perform a right rotation at \(\mathtt{u}\), making \(\texttt{u.left}\) the root of the subtree that was formerly rooted at \(\mathtt{u}\).
- With probability \(\mathtt{u\texttt{.}right\texttt{.}size/(u\texttt{.}size-1)}\), we perform a left rotation at \(\mathtt{u}\), making \(\texttt{u.right}\) the root of the subtree that was formerly rooted at \(\mathtt{u}\).

Again, we can easily verify that these are exactly the same probabilities that the removal algorithm in a `Treap` will perform a left or right rotation of \(\mathtt{u}\).

Randomized binary search trees have the disadvantage, compared to treaps, that when adding and removing elements they make many random choices, and they must maintain the sizes of subtrees. One advantage of randomized binary search trees over treaps is that subtree sizes can serve another useful purpose, namely to provide access by rank in \(O(\log \mathtt{n})\) expected time (see Exercise \(\PageIndex{10}\)). In comparison, the random priorities stored in treap nodes have no use other than keeping the treap balanced.

Exercise \(\PageIndex{1}\)

Illustrate the addition of 4.5 (with priority 7) and then 7.5 (with priority 20) on the `Treap` in Figure 7.2.1.

Exercise \(\PageIndex{2}\)

Illustrate the removal of 5 and then 7 on the `Treap` in Figure 7.2.1.

Exercise \(\PageIndex{3}\)

Prove the assertion that there are \(21,964,800\) sequences that generate the tree on the right hand side of Figure 7.1.1. (Hint: Give a recursive formula for the number of sequences that generate a complete binary tree of height \(h\) and evaluate this formula for \(h=3\).)

Exercise \(\PageIndex{4}\)

Design and implement the \(\mathtt{permute(a)}\) method that takes as input an array, \(\mathtt{a}\), that contains \(\mathtt{n}\) distinct values and randomly permutes \(\mathtt{a}\). The method should run in \(O(\mathtt{n})\) time and you should prove that each of the \(\mathtt{n}!\) possible permutations of \(\mathtt{a}\) is equally probable.

Use both parts of Lemma 7.2.1 to prove that the expected number of rotations performed by an \(\mathtt{add(x)}\) operation (and hence also a \(\mathtt{remove(x)}\) operation) is \(O(1)\).

Exercise \(\PageIndex{6}\)

Modify the `Treap` implementation given here so that it does not explicitly store priorities. Instead, it should simulate them by hashing the \(\mathtt{hashCode()}\) of each node.

Exercise \(\PageIndex{7}\)

Suppose that a binary search tree stores, at each node, \(\mathtt{u}\), the height, \(\texttt{u.height}\), of the subtree rooted at \(\mathtt{u}\), and the size, \(\texttt{u.size}\) of the subtree rooted at \(\mathtt{u}\).

- Show how, if we perform a left or right rotation at \(\mathtt{u}\), then these two quantities can be updated, in constant time, for all nodes affected by the rotation.
- Explain why the same result is not possible if we try to also store the depth, \(\texttt{u.depth}\), of each node \(\mathtt{u}\).

Exercise \(\PageIndex{8}\)

Design and implement an algorithm that constructs a `Treap` from a sorted array, \(\mathtt{a}\), of \(\mathtt{n}\) elements. This method should run in \(O(\mathtt{n})\) worst-case time and should construct a `Treap` that is indistinguishable from one in which the elements of \(\mathtt{a}\) were added one at a time using the \(\mathtt{add(x)}\) method.

Exercise \(\PageIndex{9}\)

This exercise works out the details of how one can efficiently search a `Treap` given a pointer that is close to the node we are searching for.

- Design and implement a
`Treap`implementation in which each node keeps track of the minimum and maximum values in its subtree. - Using this extra information, add a \(\mathtt{fingerFind(x,u)}\) method that executes the \(\mathtt{find(x)}\) operation with the help of a pointer to the node \(\mathtt{u}\) (which is hopefully not far from the node that contains \(\mathtt{x}\)). This operation should start at \(\mathtt{u}\) and walk upwards until it reaches a node \(\mathtt{w}\) such that \(\texttt{w.min}\le \mathtt{x}\le \texttt{w.max}\). From that point onwards, it should perform a standard search for \(\mathtt{x}\) starting from \(\mathtt{w}\). (One can show that \(\mathtt{fingerFind(x,u)}\) takes \(O(1+\log r)\) time, where \(r\) is the number of elements in the treap whose value is between \(\mathtt{x}\) and \(\texttt{u.x}\).)
- Extend your implementation into a version of a treap that starts all its \(\mathtt{find(x)}\) operations from the node most recently found by \(\mathtt{find(x)}\).

Design and implement a version of a `Treap` that includes a \(\mathtt{get(i)}\) operation that returns the key with rank \(\mathtt{i}\) in the `Treap`. (Hint: Have each node, \(\mathtt{u}\), keep track of the size of the subtree rooted at \(\mathtt{u}\).)

Exercise \(\PageIndex{11}\)

Implement a `TreapList`, an implementation of the `List` interface as a treap. Each node in the treap should store a list item, and an in-order traversal of the treap finds the items in the same order that they occur in the list. All the `List` operations \(\mathtt{get(i)}\), \(\mathtt{set(i,x)}\), \(\mathtt{add(i,x)}\) and \(\mathtt{remove(i)}\) should run in \(O(\log \mathtt{n})\) expected time.

Design and implement a version of a `Treap` that supports the \(\mathtt{split(x)}\) operation. This operation removes all values from the `Treap` that are greater than \(\mathtt{x}\) and returns a second `Treap` that contains all the removed values.

Example: the code \(\mathtt{t2 = t\texttt{.}split(x)}\) removes from \(\mathtt{t}\) all values greater than \(\mathtt{x}\) and returns a new `Treap` \(\mathtt{t2}\) containing all these values. The \(\mathtt{split(x)}\) operation should run in \(O(\log \mathtt{n})\) expected time.

Warning: For this modification to work properly and still allow the \(\mathtt{size()}\) method to run in constant time, it is necessary to implement the modifications in Exercise \(\PageIndex{10}\).

Design and implement a version of a `Treap` that supports the \(\mathtt{absorb(t2)}\) operation, which can be thought of as the inverse of the \(\mathtt{split(x)}\) operation. This operation removes all values from the `Treap` \(\mathtt{t2}\) and adds them to the receiver. This operation presupposes that the smallest value in \(\mathtt{t2}\) is greater than the largest value in the receiver. The \(\mathtt{absorb(t2)}\) operation should run in \(O(\log \mathtt{n})\) expected time.

Exercise \(\PageIndex{14}\)

Implement Martinez's randomized binary search trees, as discussed in this section. Compare the performance of your implementation with that of the `Treap` implementation.