Discussion 3A Notes (Week 10, March 12)
TA: Brian Choi ([email protected])
Section Webpage:
http://www.cs.ucla.edu/~schoi/cs32
Final Practice
BigO
Provide the complexity of each algorithm below.
1. Assume N >> 5.
for (int i = 0; i < N; i++)

O(N)
{
for (int j = 0; j < i; j++)

O(N), because i depends linearly on N
{
for (int k = 0; k < 5; k++)

O(1)
{
for (int l = 0; l < N; l + =2)

O(N), ignore the coefficient 1/2
{
cout << arr[l] << endl;
}
}
}
}
Solution:
Multiply them all to get
O(N
3
)
2. DepthFirst Traversal on a binary tree
Solution:
A depthfirst traversal will visit every node exactly once, following each edge only once.
Therefore, the complexity is O(#edges + #nodes), but we know #edges = #nodes  1 for a tree. Therefore,
O(n  1 + n) = O(2n  1) =
O(n)
.
3. BreadthFirst Traversal on a binary tree
Solution: O(n)
for the same reason.
4. Suppose there is an array of
n
(~ 1 million) elements in a random order. You want to run a search and
look for a certain item. What is the best you can do if:
1) you run a search once (i.e. “Is there 5 in the array?”)
Solution: O(n)
, you should examine every element in the array no matter what.
2) you run search million times (i.e. “Is there 5? 16? 73? ...)
Solution:
You can preprocess your array by traversing it and adding each element into a hash table. This
process takes O(n). But after doing this once, you can simply perform your searches on this hash table,
which takes
O(1)
per search.
5. Which one takes longer?
O(log n)
O(n)
O(n log n)
O(n
2
)
O(n log n)
O(n)
O(n!)
O(2
n
)
CS32: Introduction to Computer Science II
Winter 2009
Week 10, Page 1/6
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Binary Trees
6. Write a recursive function that counts the number of nodes in a binary tree. Use the following structure.
This is the end of the preview.
Sign up
to
access the rest of the document.
 Winter '08
 DavidSmallBerg
 Computer Science, hash function, Computer Science II, closest common ancestor

Click to edit the document details