You are on page 1of 12

Linked Data Structures

• For our dynamic data structures, we have


only used chains of linked nodes
• However, we can have more exotic
configurations of linked items
– Rings
Where might each of
– Trees these be useful in
– Directed Graphs practice?
https://www.baeldung.com/cs/tree-examples
Binary Trees
• Binary trees limit the root

number of child 12

nodes to two
25 17
• The root is the start
of the tree 85 -46 15

• Leaf nodes have no


56 -5 91
children leaf leaf
48 3
leaf
99 85
leaf leaf
Binary Trees
• Subtrees are the
Right
trees below a given 12
subtree of
the root
node Left subtree 25 17
of the root

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

left value right


12

left value right left value right


25 N 17

left value right left value right left value right


N 85 N N -46 N N 15 N
Binary Search Trees
• Instead of using an array, we can store elements
in a “sorted” binary tree structure, where for
each node:
– Elements less than the node value are stored in the
left subtree
– Elements greater than the node value are stored in
the right subtree 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

You might also like