Professional Documents
Culture Documents
number of child 12
nodes to two
25 17
• The root is the start
of the tree 85 -46 15
85 -46 15
56 -5 91 48 3
99 85
Binary Trees
• The depth is the
distance from the 12
root depth = 1 25 17
depth = 2 85 -46 15
depth = 3 56 -5 91 48 3
depth = 4 99 85
Implementing Binary Trees: An Example
root
5 15
-2 6 9 23
Binary Search Trees: Efficiency
• In the below tree of size 7, what is the maximum
number of comparisons that need to be done for
a single search?
• In general, approximately how many comparisons
for a tree of size n? (Trick Question!)
root
5 15
-2 6 9 23
BSTs: Pros and Cons
• Advantages (compared to arrays):
– Number of elements is not bounded
– Memory is dynamically allocated as it is
needed – less wasted memory
– If balanced, new elements can be added or
removed from the tree efficiently
• Potential Problems:
– Unbalanced subtrees can lead to inefficient
search (Example?)
http://en.wikipedia.org/wiki/Self-balancing_binary_search_tree
Keep in mind…
• ADTs are abstract, and thus do not
specify a particular implementation
• The following are implementation
strategies, not ADTs!
– BSTs
– Arrays
– Linked-lists
Using BSTs to Implement Map
• Tree nodes keep track of both keys
and values, and lookup/comparison
is only done on the key part
– For our example, that means
comparing C Strings (can use strcmp)
• If the BST is relatively balanced, we
get log2(n) efficiency
Underlying Implementation
Assignment 3 – Part 1
• Implement a BST-based map (from C
Strings to ints), using the provided map.h
• Be sure to test out your implementation in
main in a separate .c file
• Remember that you will need to allocate
new nodes whenever you add a new key to
your map
• Most of these functions can be
implemented recursively, which is often
easier than implementing them iteratively