Binary Search Trees




CS146

Chris Pollett

Apr 7, 2014

Outline

Introduction

A Multiple-Array Representation of Objects

An example of a linked-list in multiple-array representation

A Single-Array Representation of Objects

Example Single-Array Implementation of Pointers

Allocating and Freeing Objects

More on the Free List

Examples of operations on a free list

Quiz (Sec 5)

Which of the following statements is true?

  1. A dynamic set supporting insert, delete, and set membership is called a dictionary
  2. Stacks are dynamics sets where the insert operation is First In First Out (FIFO).
  3. Last week, we gave an `O(1)` algorithm for LIST-SEARCH(L,k).

Quiz (Sec 6)

Which of the following statements is true?

  1. Queues are dynamics sets where the insert operation is Last In First Out (LIFO).
  2. Last week, we gave an `O(1)` algorithm for LIST-DELETE(L, x).
  3. A dynamic set supporting insert, delete, and set membership is called a dictionary

Binary Search Trees

What is a Binary Search Tree?

Example Binary Search Trees

Tree Traversals

INORDER-TREE-WALK run-time

Theorem. If `x` is the root of an `n`-node subtree, then the call INORDER-TREE-WALK(x) takes `Theta(n)` time.

Proof. Let `T(n)` denote the time taken by INORDER-TREE-WALK(x). Since INORDER-TREE-WALK visits all `n` nodes of the subtree, we have `T(n) = Omega(n)`. It remains to show that `T(n) = O(n)`.

On an empty tree INORDER-TREE-WALK takes a fixed constant `c gt 0` amount of time. So `T(0) = c`.

For `n gt 0`, suppose `x` has a `k`-node left subtree and a `n-k-1` node right subtree. The time to perform INORDER-TREE-WALK(x) is bounded by `T(n) le T(k) + T(n - k -1) + d` where `d gt 0` is the time to execute the body of INORDER-TREE-WALK(x) ignoring the recursive calls.

We use the substitution method to show that `T(n) = O(n)`, by proving that `T(n) le (c + d)n +c`. For `n = 0`, we have `(c + d)cdot 0 +c = c = T(0)`. For `n gt 0`, we have:
`T(n) le T(k) + T(n - k - 1) +d`
`qquad = ((c+d)k +c) + ((c+d)(n-k -1) + c) +d` by the induction hypothesis
`qquad = (c+d)n + c - (c + d) + c + d`
`qquad = (c+d)n +c`, so the induction holds, completing the proof. QED.